Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a reasonable way to use C# dynamic?

Tags:

c#

dynamic

Pardon the crude example. I have an encoder that returns an interface. Instead of using "is" and "as" to get the object that implements the interface, I would like to use dynamic to access a field property on the object. The field property is NOT on the interface, but is common across all objects that implement the interface.

EDIT: I should also mention that I do not have control of the encoder or it's interfaces so I can not modify them.

public class Program
{
  public Program()
  {
    dynamic temp = GetInterface();
    string s = temp.Blah;
    temp.Blah = s;
  }

  private ITest GetInterface()
  {
    return new Test();
  }
}
public interface ITest
{
}
public class Test : ITest
{
  public string Blah { get; set; }
}    
like image 442
ConditionRacer Avatar asked Feb 21 '23 11:02

ConditionRacer


2 Answers

That's not a very good example. If all (or many) implementations of the interface have the field, then create an abstract implementation of the interface with the field, have the implementations derive from the abstract class instead of inherit the interface. Then you can use the abstract class rather than the interface.

like image 193
Kieren Johnstone Avatar answered Feb 24 '23 02:02

Kieren Johnstone


The use will work just fine. The dynamic binding will look through the type and find the underlying property. From that perspective it's valid.

However if it's a property that's common to all implementations of the interface then why would you not just add it to the interface? If it's a property you'd rather not make public then why not have a second internal interface which contains the property?

like image 27
JaredPar Avatar answered Feb 24 '23 01:02

JaredPar