I'm trying to use duck typing using reflection in C#. I have an object of some random type and I want to find if it implements an interface with a specific name and if it does - retrieve a reference to that interface subobject so that I can later read (get) a property value via that interface.
Effectively I need as
using Reflection.
The first part is easy
var interfaceOfInterest =
randomObject.GetType().GetInterface("Full.Interface.Name.Here");
which will either retrieve the interface description or null. Let's assume it's not null.
So now I have an object reference to an object that surely implements that interface.
How do I have the "cast" like retrieval of the subobject using Reflection only?
You don't need to, simply access the properties of the interface, through the interface type, but whenever you need to pass an instance, simply pass the original object instance.
Here is a LINQPad program that demonstrates:
void Main()
{
var c = new C();
// TODO: Check if C implements I
var i = typeof(I);
var valueProperty = i.GetProperty("Value");
var value = valueProperty.GetValue(c);
Debug.WriteLine(value);
}
public interface I
{
string Value { get; }
}
public class C : I
{
string I.Value { get { return "Test"; } }
}
Output:
Test
If you want to access it much more using names:
void Main()
{
var c = new C();
// TODO: Check if C implements I
var i = c.GetType().GetInterface("I");
if (i != null)
{
var valueProperty = i.GetProperty("Value");
var value = valueProperty.GetValue(c);
Debug.WriteLine(value);
}
}
public interface I
{
string Value { get; }
}
public class C : I
{
string I.Value { get { return "Test"; } }
}