How to create List<T> instance in C# file using Reflection

Ananya picture Ananya · May 6, 2011 · Viewed 17.6k times · Source

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...

Answer

Andras Zoltan picture Andras Zoltan · May 6, 2011

Rather than question your motives or try to unpick what you're doing - I'm just going to answer the question in the title.

Given you have a type instance listElemType that represents the type argument that is to be passed to the List<> type at runtime:

var listInstance = (IList)typeof(List<>)
  .MakeGenericType(listElemType)
  .GetConstructor(Type.EmptyTypes)
  .Invoke(null);

And then you can work with the list through it's IList interface implementation.

Or, indeed, you can stop at the MakeGenericType call and use the type it generates in a call to Activator.CreateInstance - as in Daniel Hilgarth's answer.

Then, given a target object whose property you want to set:

object target; //the object whose property you want to set
target.GetType()
  .GetProperty("name_of_property")        //- Assuming property is public
  .SetValue(target, listInstance, null);  //- Assuming .CanWrite == true 
                                          //  on PropertyInfo

If you don't know the properties of the type represented by target, then you need to use

target.GetType().GetProperties();

to get all the public properties of that instance. However just being able to create a list instance isn't really going to be able to help you there - you'll have to have a more generic solution that can cope with any type. Unless you're going to be specifically targetting list types.

Sounds to me like you might need a common interface or base...