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

13,608

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.

Share:
13,608
Zaid Masud
Author by

Zaid Masud

Updated on June 04, 2022

Comments

  • Zaid Masud
    Zaid Masud almost 2 years

    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'.