I have the following usecase. There'a ISpecificInterface
interface with SpecificProperty
property that is explicitly implemented by SpecificInterfaceImplementation
class. My code implements the callback that is passed object
which refers to the SpecificInterfaceImplementation
instance. The problem gets worse - there're several different versions of ISpecificInterface
each having SpecificProperty
with the same type (of the property) possible and my program needs to work with any of them and preferably without code duplication.
I'd use duck typing via C# dynamic
:
dynamic theInterface = theObjectPassed;
String propertyValue = theInterface.SpecificProperty;
but since the property is explicitly implemented I get RuntimeBinderException
with the following text
'SpecificNamespace.SpecificInterfaceImplementation' does not contain a definition for 'SpecificProperty'
and so I need to somehow get to the interface. I would not use a cast because the cast would expose a specific version of the interface and work only for that version and duck typing would be gone. So I use Reflection directly:
Type objectType = theObjectPassed.GetType();
var specificInterface = objectType.GetInterface("SpecificInterface");
var specificProperty = specificInterface.GetProperty("SpecificProperty");
var propertyValue = specificProperty.GetValue(specificInterface);
and it works just fine but it requires a ton of extra code.
Can I somehow use dynamic
s and duck typing to avoid this ton of code with Reflection?