Using this code I get the property of some object by its name:
string propName = "Buttons"; // getting this runtime
Type t = container.GetType();
PropertyInfo p = t.GetProperty(propName);
object prop = p.GetValue(container, null);
the Type of property depends on property name, but all properties have implemented the IList interface and therefore all of them have Add() method. Now I want to be able to use this method to add elements to that property. But I can’t call this method on object type. I need somehow to cast it runtime, but before that I have to somehow use prop.Add(), which of course triggers a compile error now. Is there any way to call a method at runtime independently of the object type (of course being sure that object has that method).
P.S. if the question isn’t clear I can add more details.
Simply cast the result to an
IList?You will then get access to
IListmembers. Of course, this assumes you are correct in that they are alwaysIListotherwise you will start to getInvalidCastExceptions.Alternatively, but I wouldn’t advise this, you could always make the assumption that the
Addmethod exists and duck-type it using dynamic:The above will resolve at runtime using the DLR. It will try to find a public
Addmethod that takes a singlestringparameter.