How can I implement Interface for Node class

I'm trying to implement interface for Node class in CSharp.

NodeInterfaces.cs

public interface INode<T>
{
    T Value { get; set; }
    Node<T> Left { get; set; }
    Node<T> Right { get; set; }
}

Nodes.cs

public class Node<T> : INode<T>
{
    T Value { get; set; }
    Node<T> Left { get; set; }
    Node<T> Right { get; set; }
}

BUT cyclic dependency error occurs I've tried to understand how can I implement it in another way, but I have no idea...

So The only solution I've come to is

NodeInterfaces.cs

public interface INode<T, N> where N : class
{
    T Value { get; set; }
    N Left { get; set; }
    N Right { get; set; }
}

Nodes.cs

public class Node<T> : INode<T>
{
    T Value { get; set; }
    Node<T> Left { get; set; }
    Node<T> Right { get; set; }
}

Is it a good practice, or which ways of fixing this cycling dependecies problems are applicable too? I need your advices how would be better to implement this interface, or it would be better without any interfaces (but I want to do it)

Upvotes: 1

Views: 67

Answers (1)

PMF
PMF

Reputation: 17288

There is no cyclic dependency here. Your code should work just fine. This isn't C++, where this would indeed be a cyclic dependency (unless the Node elements are pointers). The only thing that's a bit ugly is that you would normally have an interface only return interfaces, not concrete classes, thus you would have

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

To satisfy the interface now (and still being able to access the class type), you now have to implement the interface explicitly, though:

public class Node<T> : INode<T>
{
    T Value { get; set; }
    INode<T> INode<T>.Left => Left;
    INode<T> INode<T>.Right => Right;
    Node<T> Left { get; set; }
    Node<T> Right { get; set; }
}

Upvotes: 4

Related Questions