The type 'T' cannot be used as type parameter in the generic type or method error when type is known
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.
Zaid Masud
Updated on June 04, 2022Comments
-
Zaid Masud almost 2 years
Consider the following code sample, where
Concrete
derives fromBase
: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'.