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'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With