HI, I have a requirement to create instance for list object at runtime using reflection. For example I have 2 classes like below,
class Class1
{
List<Class2> class2List;
public List<Class2> Class2List
{
get;set;
}
}
class Class2
{
public string mem1;
public string mem2;
}
After creating the instance of Class1
at Runtime in another class Class3
, I want to assign values to all the properties of the class. In this case, Class2List
is a property of List<Class2>
. At Runtime, I don't know the class type of List<Class2>
. How can I initialize the property i.e. List<Class2>
inside class3 at runtime.
Any suggestions are greatly appreciated...
Type.EmptyTypes
for GetConstructor, and passnull
to Invoke. Also, you'll have to cast the object returned by Invoke:var listInstance = (IList)(typeof(List<>) .MakeGenericType(listElemType) .GetConstructor(new Type[0]) .Invoke(new object[0]));
– Wendywendye