Search code examples
c#listc#-4.0reflectionwpfdatagrid

how to create a list of type obtained from reflection


I have a code which looks like this :

Assembly assembly = Assembly.LoadFrom("ReflectionTest.dll");
Type myType = assembly.GetType(@"ReflectionTest.TestObject");
var x = Convert.ChangeType((object)t, myType);   

//List<myType> myList = new List<myType>();
//myList.Add(x);

The commented part of the code is where I am stuck. I am getting some objects from a service and the conversion works fine too. I am trying to populate a list of such objects and will later bind to WPF DataGrid.

Any help appreciated!


Solution

  • var listType = typeof(List<>).MakeGenericType(myType)
    var list = Activator.CreateInstance(listType);
    
    var addMethod = listType.GetMethod("Add");
    addMethod.Invoke(list, new object[] { x });
    

    You might be able to cast to IList and call Add directly instead of looking up the method with reflection:

    var list = (IList)Activator.CreateInstance(listType);
    list.Add(x);