Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Type objects as Type Parameters for Generics in C#

Tags:

c#

types

generics

I cannot find a way to use a first-class Type object (System.Type instance) as a Type Parameter in a generic construction in C# 3.0 / .NET 3.5. Below is a simplified example of what I want to do:

public void test()
{
    Type someType = getSomeType(); // get some System.Type object

    MyGeneric<someType> obj = new MyGeneric<someType>();  // won't compile
}

Is there any way to use the someType object as a type parameter for a generic?

like image 261
sgibbons Avatar asked Sep 23 '09 16:09

sgibbons


2 Answers

You can dynamically create an instance of the type :

public void test()
{
    Type someType = getSomeType(); // get some System.Type object
    Type openType = typeof(MyGeneric<>);
    Type actualType = openType.MakeGenericType(new Type[] { someType });
    object obj = Activator.CreateInstance(actualType);
}

However you can't declare a variable of this type, since you don't know the actual type statically.

like image 147
Thomas Levesque Avatar answered Nov 02 '22 01:11

Thomas Levesque


You're trying to determine your type argument at runtime. .Net generics require that the type arguments are known at compile time. There's really no way to do that outside of switching on the type. You may be able to get a handle to the method via reflection and invoke it, but that's ugly.

like image 40
Joel Coehoorn Avatar answered Nov 02 '22 01:11

Joel Coehoorn