Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Generic<T> type instance with a variable containing the Type

Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?

Type k = typeof(double); List<k> lst = new List<k>(); 
like image 346
Chris Avatar asked Jan 16 '10 21:01

Chris


People also ask

Can you create instances of generic type parameters?

Yes, this is nice especially if the generic class is abstract, you can do this in the concrete subclasses :) @TimKuipers The <E> in class Foo<E> is not bound to any particular type.

How do you create a generic variable in Java?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.


2 Answers

Yes, there is:

var genericListType = typeof(List<>); var specificListType = genericListType.MakeGenericType(typeof(double)); var list = Activator.CreateInstance(specificListType); 
like image 103
David M Avatar answered Oct 04 '22 15:10

David M


A cleaner way might be to use a generic method. Do something like this:

static void AddType<T>()     where T : DataObject {     Indexes.Add(typeof(T), new Dictionary<int, T>()); } 
like image 26
Bryan Legend Avatar answered Oct 04 '22 17:10

Bryan Legend