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

Time:03-08

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

CodePudding user response:

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

CodePudding user response:

This is how you can make the classes that inherit from the interface and implement the method with a specified return type of type of the derived class

  interface IDeepCopy<T>
    {
        T testMethod();

    }
    class Test1 : IDeepCopy<Test1>
    {
        public Test1 testMethod()
        {
            throw new NotImplementedException();
        }
    }
  •  Tags:  
  • c#
  • Related