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; }
}
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With