Steve Kero
Steve Kero

Reputation: 713

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?

Upvotes: 3

Views: 899

Answers (2)

Alessandro D'Andria
Alessandro D'Andria

Reputation: 8868

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

Upvotes: 11

slugster
slugster

Reputation: 49974

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.

Upvotes: 2

Related Questions