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


The problem is that classes do 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>();

      



Frequency of covariance and contravariance

+1


source


You need covariance (mark the type parameter with a T

word out

):

interface IX<out T> {}

      

This is only allowed with interface types (and delegate types). And the type B

must be a reference type ( class

like here, that's ok).



Then it's ok:

IX<B> ixb = ...;
IX<A> ok = new IX<B>();

      

+1


source







All Articles