Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize generic object from a System.Type

Tags:

I need to create a generic type, but I do not know the type at compile time. I would like to do this:

Type t = typeof(whatever);
var list = new List<t>

this won't compile, because t is not a valid type. But it does know all about a valid type. Is there a way to dynamically create the generic list from a System.Type like this? I may need reflection, and that's ok, I am just a bit lost here.

like image 968
captncraig Avatar asked May 14 '10 03:05

captncraig


People also ask

How to Get generic type in c#?

If you call the GetGenericTypeDefinition method on a Type object that already represents a generic type definition, it returns the current Type. An array of generic types is not itself generic. In the C# code A<int>[] v; or the Visual Basic code Dim v() As A(Of Integer) , the type of variable v is not generic.

What is the object type in C#?

The object type is an alias for System. Object in . NET. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from System.


1 Answers

Like this:

Type t;
Type genericListType = typeof(List<>).MakeGenericType(t);
object list = Activator.CreateInstance(genericListType);

Note that you can only assign it to a variable of type object. (Although you can cast to to the non-generic IList interface)

To use the list variable, you'll probably need reflection.

like image 79
SLaks Avatar answered Sep 30 '22 04:09

SLaks