8

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?

1
  • I personally used a Switch. This may not be applicable everywhere... I wish it could be as in your example. Commented Dec 13, 2011 at 21:14

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

4 Comments

If anyone comes past this post, in C# 4.0 the dynamic keyword allows you to declare variables for which the compile-time type checking is disabled.
@JacobBundgaard, yes, but it is unrelated to the OP's problem. It doesn't allow you to create instances of generic types when you don't know the type parameter at compile time.
I don't think it is. A dynamic declaration will allow you to call the methods of the MyGeneric object created via reflection, while an object declaration won't. Consider that MyGeneric has a method MyMethod. Then this snip of code won't work: object obj = Activator.CreateInstance(actualType); obj.MyMethod();, while this will: dynamic obj = Activator.CreateInstance(actualType); obj.MyMethod();
I'm sorry if it seemed like I was trying to solve the OP's problem. The OP is probably past this, now four years later, while people passing by might benefit from knowing of a newer language feature related to the problem.
9

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.

1 Comment

+1 Thomas shows how to do it but you explain better why reflection is required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.