Unable to compile code containing generics and inner classes

I am trying to implement a Singlely Linked List. I can not compile the following code. I removed a lot of unnecessary code that does not apply to this question from the snippet below:

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; } } 

Statement marked # 2 fails with error - Cannot implicitly convert type 'SinglyLinkedList<T>.SinglyNode<T>' to 'SinglyLinkedList<T>.SinglyNode<T> Program.cs

The statement labeled # 1 is semantically similar to # 2 and compiles. What makes a program compile? Are there any general rules related to native + inner classes that make the above code not compile?

Please note that the above code snippet is part of my training by reinventing the wheel and not being production code.

+4
source share
1 answer

Inner classes declare their own completely different T

Just remove T from inner classes and everything will be fine:

 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; } } 
+9
source

All Articles