Let's say we have these types:
class A {}
class B : A {}
class X<T> {}
Why we can't do this?
X<A> var = new X<B>();
Is there any workaround available?
[Edit] I tried to use covariance but it failed because I want to access a property inside X that is of type T and C# does not allow using type T in the interface:
interface IX<out T> {
T sth {set; get;}
}
class X<T>: IX<T> {
T sth { set; get; }
}
[Edit 2] I also tried this but it failed:
class X<T> where T : A
{
public T sth { set; get; }
public static implicit operator X<T>(X<B> v)
{
return new X<T>
{
sth = v.sth,
};
}
}
It's strange that C# does not allow to the casting for 'sth'.
The problem is that classes does not support Covariance and Contravariance, only interfaces:
class A { }
class B : A { }
class X<T> : P<T> { }
interface P<out T>
{
}
...
P<A> var = new X<B>();
Covariance and Contravariance FAQ
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