How to convert derived class inside a wrapper class generic in c#

65 views Asked by At
using System;

class X {}
class Y: X {}

class Wrapper<T> where T : X {}

public class HelloWorld
{
    public static void Main(string[] args)
    {
        Wrapper<Y> y = new();
        
        Wrapper<X> x = y; // Error here
    }
}

The error is error CS0029: Cannot implicitly convert type 'Wrapper<Y>' to 'Wrapper<X>'

Here I want to convert Wrapper<Y> into Wrapper<X>.

How can I do this?

2

There are 2 answers

4
Rezo Megrelidze On BEST ANSWER

You can make it work by having a covariant interface. And you won't need the where clause either.

class X { }
class Y : X { }

interface IWrapper<out T> {
    
}

class Wrapper<T> : IWrapper<T> 
{
    
}

public class HelloWorld
{
    public static void Main(string[] args)
    {
        IWrapper<Y> y = new Wrapper<Y>();

        IWrapper<X> x = y;
    }
}
2
abel1502 On

You cannot, in the general case. Consider the following example: y is a List<Y>, x is a List<X>. This means it should be legal to do x.Add(new X()) (because you can do it with a List<X>), but if it is actually a List<Y>, this would be an illegal operation, since new X() is not of type Y. It doesn't work the other way around either, because that would break reading operations like y[0]. This is called template covariance and contravariance, and you can read more about it here