I have a little problem for you guys.
I would like to do this:
Type[] classes = new Type[]{ Class1, Class2 };
foreach(Type t in classes){
List<t> list = new List<t>();
}
Is there some way to do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You cannot cast to a generic type at runtime, because the type in the generic needs to be resolved at compile time.
You can create a generic type in a dynamic manner using reflection, but unless you hard-code the cast, all you get in return is an object.
I cannot really tell what it is you want, I have to agree with a comment this is an XY problem. I would be inclined to make the presumptuous statement that there is a design issue somewhere that this is trying to solve, instead of addressing the design issue directly, or asking the question of what you are trying to achieve directly.
You can use the following code to create the type, then the
dynamictype can be used to duck type the various members ofList<T>without knowing/caring that it is a list or whatTis:The above sample duck types the
Addmethod and the Indexer. The DLR does the type handling and the duck typing at runtime – knowing that1is anint, for example.Just to clarify, I likely wouldn’t use such code in production (unless you requirements are very specific to need this) and any issues with type-mismatching will occur at run time; so you either need to type very accurately (limited IntelliSense) or have good error handling.
Thanks to this blog post for the
CreateGenericmethod.This assumes .NET 4 with the new CLR. As @MartinLiversage has also pointed out, this particular sample assumes that you are utilising the list in a sort-of-strongly-typed manner. In my example I am passing an
intto aList<int>hidden in adynamic.We have been on .NET 4 almost since it was released. We have a large application with an even larger code base.
dynamicisn’t used once in the application, and only a few times in the test code base. That isn’t to say “don’t use it”, it’s to say “most of the time, you don’t need it”.