Search code examples
c#genericsderived-class

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


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?


Solution

  • 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;
        }
    }