Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading