1

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)

3
  • 5
    "BUT cyclic dependency error occurs " - what cyclic dependency error? Do you have interface and implementation in different projects? Commented Feb 10 at 20:36
  • That could be a "curiously recursive" constraint; INode<T, N> where N : INode<T,N>. Commented Feb 11 at 5:50
  • Yes, my inerface and class implementation in different projects, It's my fault, You're right, there's no cyclic dependency, if it will be in one project. Commented Feb 11 at 5:54

1 Answer 1

4

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.