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

C# interface method with generic return type of implements interface (Bounds)

Let’s say I have a DeepCopyable interface that looks like this:

public interface DeepCopyable
{
    public T DeepCopy<T>() /* where T : DeepCopyable */; // i know this doesn't work
}

I want to make sure that the implementing classes implement like this:
I don’t know how to archive this with an interface, how do I specify the return type correctly to be of type of the implementing class?

public class A : DeepCopyable
{
    public int a { get; set; } = 0;
    public B b { get; set; } = new B();

    public A DeepCopy() 
    {
        return new A()
        {
            a = a,
            b = b.DeepCopy()
        };
    }
}

public class B : DeepCopyable
{
    public int a { get; set; } = 0;

    public B DeepCopy()
    {
        return new B()
        {
            a = a
        };
    }
}
public class C : DeepCopyable
{
    public int a { get; set; } = 0;

    public B DeepCopy() //This Should be not allowed
    {
        return new B()
        {
            a = a
        };
    }
}

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 :

A simple way of doing this is like this:

public interface IDeepCopyable<T>
    where T : IDeepCopyable<T>
{
    T DeepCopy();
}

public class A : IDeepCopyable<A>
{
    public int a { get; set; } = 0;
    public B b { get; set; } = new B();

    public A DeepCopy() 
    {
        return new A()
        {
            a = a,
            b = b.DeepCopy()
        };
    }
}

public class B : IDeepCopyable<B>
{
    public int a { get; set; } = 0;

    public B DeepCopy()
    {
        return new B()
        {
            a = a
        };
    }
}
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