Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner generic type same as outer - 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 the compiler warning: Type parameter 'T' has the same name as the type parameter from outer type 'Tree<T>' Well, of course it's the same name, they should be the same type. (In fact, since the Node class is private and thus can never be accessed outside of the Tree class, they are guaranteed to be the same type. Is this compiler warning just BS which I can safely ignore? Or is there some good reason why I should give the inner class a different generic name (other than just to make the warning go away)?

(I saw this question, which is about the warning itself, but this is clearly a different scenario. The types are guaranteed to be the same, as Node's are only created and accessed within the context of Tree, so there's no chance of confusion.)

like image 910
Darrel Hoffman Avatar asked Jun 17 '13 19:06

Darrel Hoffman


2 Answers

You're misunderstanding nested type parameters.

The compiler is warning you about constructed types like Tree<int>.Node<string>. Such types will make your life miserable. (I speak from personal experience)

If you want to use the outer T in Node, you shouldn't make Node generic.

In general, there are very few reasons to nest one generic type within a different one.

like image 185
SLaks Avatar answered Oct 25 '22 09:10

SLaks


What you want is probably:

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 dont need to redefine it again.

like image 29
fcuesta Avatar answered Oct 25 '22 10:10

fcuesta