Reputation: 41
I created a list using method from this post Create list of variable type
Assembly assembly = Assembly.Load("ConsoleApplication4");
Type mytype = assembly.GetType("ConsoleApplication4.TestClass");
Type genericList = typeof(List<>).MakeGenericType(mytype);
var mylist = Activator.CreateInstance(genericList);
my question is,after I create the list, how can I use the list in a function like following:
public void TestFunction<T>(List<T> mylist)
{
//do something here
}
Upvotes: 1
Views: 75
Reputation: 21752
you could simply change the last line where you instantiate the list
dynamic mylist = Activator.CreateInstance(genericList);
That way the compiler won't try to infer the (runtime) type of myList but will defer this task to the DLR which in your case will be happy to tell you that it is some List<mytype>
If you at some point know the concrete type of mylist
you can of course also use a simple cast
TestFunction((List<knownType>)mylist);
which one to prefer is mainly a matter of taste, there might be performance differences between the two but compared to the reflection based instantiation that difference is probably not going to be the bottleneck but if performance is of main concern use a profiler.
The reason why I suggest using dynamic at the instantiation site instead of in the method signature is to make most of the code statically typed so that the compiler can check most of the code. By using dynamic in the method signature you will make all calls of that method into dynamic calls whereas if you make the mylist dynamically typed you are only make the statements using mylist into dynamic calls.
Upvotes: 1
Reputation: 1557
You'd lose static type analysis and compile-time checking (then again, given that you're working with reflection that's already happened), so you could just re-write your TestFunction
as:
public void TestFunction(dynamic myList)
{
// do something here
}
Upvotes: 1
Reputation: 147
You can not use the instance of mylist in the way you want, because the Compiler can not infer the closed type of List. You can only work with further reflection methods or inspect it with open generic types.
Upvotes: 0