Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type 'T' cannot be used as type parameter in the generic type or method error when type is known

Consider the following code sample, where Concrete derives from Base:

class Base{}
class Concrete : Base {}

static void Foo<T>() where T : Base
{
    if (typeof(Concrete).IsAssignableFrom(typeof(T)))
    {
        var x = new Bar<T>(); // compile error on this line
    }
}

class Bar<T> where T : Concrete
{
}

On the line where I am having the compile error, I have already checked that the generic argument is assignable to the Concrete type. So in theory I believe there should be a way to create an instance of the Bar class.

Is there any way I can remove the compile error? I cannot think of a way to cast the argument.


Full text of compile error:

Error 14 The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Bar'. There is no implicit reference conversion from 'T' to 'Concrete'.

like image 704
Zaid Masud Avatar asked Nov 06 '12 14:11

Zaid Masud


1 Answers

The compiler has no way to know that T, which is currently constraint to Base is actually Concrete, and that even if you test it before.

So:

Type type = typeof(Bar<>);
Type generic = type.MakeGenericType(typeof(T));
var x = Activator.CreateInstance(generic); 

Don't let it the chance to do it.

like image 173
LightStriker Avatar answered Oct 07 '22 10:10

LightStriker