ConditionRacer
ConditionRacer

Reputation: 4498

Is this a reasonable way to use 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; }
}    

Upvotes: 4

Views: 185

Answers (5)

Jeb
Jeb

Reputation: 3789

Yes that is acceptable and would compile. However, this feels like an anti pattern in my point of view. What happens when you rename the Blah property in the class one day? Sure it'll compile but...

Note: from your edit, I understand you can't add the property to ITest. So I would create a new interface "ITest2" with the property which Test implements, and let the compiler do the work for you.

Upvotes: 1

Daniel Earwicker
Daniel Earwicker

Reputation: 116654

Why not add Blah to ITest? That is:

public interface ITest
{
    public string Blah { get; set; }
}

Upvotes: 0

JaredPar
JaredPar

Reputation: 754545

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?

Upvotes: 3

Daniel Mann
Daniel Mann

Reputation: 58980

In the specific case you mentioned, it sounds like the property should be a member of the interface.

Upvotes: 0

Kieren Johnstone
Kieren Johnstone

Reputation: 41983

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.

Upvotes: 4

Related Questions