Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Casting Generic Child Type to Parent

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'.

like image 224
HamedH Avatar asked Sep 03 '25 17:09

HamedH


1 Answers

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

like image 107
Backs Avatar answered Sep 06 '25 20:09

Backs