C # Casting Generic Child Type for Parent
Let's say we have the following types:
class A {}
class B : A {}
class X<T> {}
Why can't we do this?
X<A> var = new X<B>();
Is there access to a workaround?
[edit] I tried to use covariance but it didn't work because I want to access a property inside X that is of type T and C # does not allow 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 # doesn't allow casting for 'sth'.
+3
source to share
2 answers