The internal generic type is the same as the external - compiler warning

So I have a tree class:

public class Tree<T> : IEnumerable where T : IComparable<T> { private Node<T> root = null; ... private class Node<T> : IEnumerable<T> where T : IComparable<T> { private Node<T> left, right; ... } } 

It works fine, but I get a compiler warning: Type parameter 'T' has the same name as the type parameter from outer type 'Tree<T>' Well, of course, this is the same name, they must be of the same type. (In fact, since the Node class is private and therefore can never be accessed outside the Tree class, they are guaranteed to be of the same type. Is this compiler a warning only about BS, which I can safely ignore? What should I give the inner class something else generic name (other than to warn him)?

(I saw this question , which concerns the warning itself, but this is clearly a different scenario. It is guaranteed that the types will be the same as Node created and available only in the Tree context, so there is no possibility of confusion.)

+4
source share
2 answers

You misunderstand the parameters of a nested type.

The compiler warns you about built types, such as Tree<int>.Node<string> . These types will make your life miserable. (I speak from personal experience)

If you want to use external T in Node , you should not make Node generic.

In general, there are very few reasons to embed one generic type in another.

+9
source

You probably want:

 public class Tree<T> : IEnumerable where T : IComparable<T> { private Node root = null; ... private class Node: IEnumerable<T> { private Node left, right; ... } } 

If you want the inner class to have the same T, you no longer need to override it.

+3
source

Source: https://habr.com/ru/post/1486681/


All Articles