Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface polymorphism in C#

I have a code like this:

public interface INode
{
    INode Parent { get; set; }
    // ......
}

public interface ISpecificNode : INode
{
    new ISpecificNode Parent { get; set; }
    // ......
}

public class SpecificNode : ISpecificNode
{
    ISpecificNode Parent { get; set; }
    // ......
}

This code gives a compilation error, because INode.Parent is not implemented. However, I don't need duplicate Parent properties.
How can I solve this issue?

like image 261
Steve Kero Avatar asked Feb 04 '26 17:02

Steve Kero


2 Answers

I think you're looking for something like this:

public interface INode<T> where T : INode<T>
{
    T Parent { get; set; }
}

public interface ISpecificNode : INode<ISpecificNode>
{
}

public class SpecificNode : ISpecificNode
{
    public ISpecificNode Parent { get; set; }
}
like image 144
Alessandro D'Andria Avatar answered Feb 06 '26 05:02

Alessandro D'Andria


This is not inheritance / overriding like you get with classes - interfaces do not inherit other interfaces, they implement them.

This means anything that implements ISpecificNode must also implement INode.

I would suggest you remove the line

new ISpecificNode Parent { get; set; }

there is probably no need for it. Alternatively you could look to implement INode on an abstract base class, override it with the concrete SpecificNode class, and use property hiding to hide the INode version of the property.

like image 39
slugster Avatar answered Feb 06 '26 06:02

slugster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!