I have a code which looks like this :
Assembly assembly = Assembly.LoadFrom(\"ReflectionTest.dll\");
Type myType = assembly.GetType(@\"ReflectionTest.TestObject\
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);
You need MakeGenericType method:
var argument = new Type[] { typeof(myType) };
var listType = typeof(List<>);
var genericType = listType.MakeGenericType(argument); // create generic type
var instance = Activator.CreateInstance(genericType); // create generic List instance
var method = listType.GetMethod("Add"); // get Add method
method.Invoke(instance, new [] { argument }); // invoke add method
Alternatively you can cast your instance to IList
and directly use Add
method.Or use dynamic
typing and don't worry about casting:
dynamic list = Activator.CreateInstance(genericType);
list.Add("bla bla bla...");
Try this:
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(myType);
var myList = (IList)Activator.CreateInstance(constructedListType);
myList.Add(x);
The list will not be strongly-typed but you can add items as objects.