Search code examples
c#oopinheritanceinterface

Interface inheritance issue


I have IBinaryNode interface and IRedBlackNode interface that inherits from IBinaryNode.

public interface IBinaryNode<T>
{
    public IBinaryNode<T>? Left  { get; set; }
    public IBinaryNode<T>? Right { get; set; }
    public T              Value { get; }

}

public interface IRedBlackNode<T> : IBinaryNode<T>
{
    IRedBlackNode<T>? Parent  { get; set; }
    bool              IsBlack { get; set; }
}

How can I use IRedBlackNode instead of IBinaryNode in the properties of the following class? I thought that if IRedBlackNode implements IBinaryNode then I can do it but I get type error that says that it must be IBinaryNode instead.

private class RedBlackNode : IRedBlackNode<T>
{
    public IRedBlackNode<T>? Parent  { get; set; }
    public IRedBlackNode<T>? Left    { get; set; }
    public IRedBlackNode<T>? Right   { get; set; }
    public bool              IsBlack { get; set; }
    public T                 Value   { get; }
}

Solution

  • Actually, you can't. Consider you have an instance of RedBlackNode, then it can be cast to IBinaryNode<T> and any other IBinaryNode<T> can be assigned to its Right property.

    But, if you want to restrict class RedBlackNode to have only instances of IRedBlackNode<T> in its Right property, you can do it via explicit interface implementation:

    public IRedBlackNode<T> Right { get; set; }
    
    IBinaryNode<T> IBinaryNode<T>.Right
    {
      get => Right;
      set => Right = (IRedBlackNode<T>)value;
    }
    

    P.S. If you only have getters on Left and Right it will work through covariance, but you have also setters