Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to compile code containing generics and inner classes

I am trying to implement Singly Linked List. I am not able to compile the following code. I have removed lot of unnecessary code which is not relevant for this question from the below snippet:

public class SinglyLinkedList<T>
{
    public SinglyLinkedList()
    {
    }

    private SinglyNode<T> _head = null;

    private class SinglyNode<T>
    {
        public T Data { get; set; }
        public SinglyNode<T> Next { get; set; }
    }

    private class Enumerator<T>
    {
        public Enumerator(SinglyLinkedList<T> list)
        {
            _list = list; //#1
            _head = list._head; //#2
        }

        private SinglyLinkedList<T> _list = null;
        private SinglyNode<T> _head = null;
    }
}

The statement marked #2 is failing with the error - Cannot implicitly convert type 'SinglyLinkedList<T>.SinglyNode<T>' to 'SinglyLinkedList<T>.SinglyNode<T> Program.cs

The statement marked #1 is semantically similar to #2 and it is compiling. What is stopping the program to compile? Are there any genercis + inner classes related rules that are causing the above code to not compile?

Please make a note that the above code snippet is part of my learning by reinventing the wheel and is not a production code.

like image 518
Anand Patel Avatar asked Jan 15 '23 13:01

Anand Patel


1 Answers

The inner classes each declare their own completely different T.

Just remove the T from the inner classes and all will be well:

public class SinglyLinkedList<T>
{
    public SinglyLinkedList()
    {
    }

    private SinglyNode _head = null;

    private class SinglyNode
    {
        public T Data { get; set; }
        public SinglyNode Next { get; set; }
    }

    private class Enumerator
    {
        public Enumerator(SinglyLinkedList<T> list)
        {
            _list = list; //#1
            _head = list._head; //#2
        }

        private SinglyLinkedList<T> _list = null;
        private SinglyNode _head = null;
    }
}
like image 144
Marc Gravell Avatar answered Jan 17 '23 01:01

Marc Gravell