C#C
C#11mo ago
Faker

Purpose and use of nested classes in C#

Hello guys, sorry to disturb you all; can someone explain the idea of using nested classes in C# please. For example, consider the following code:

C#
// Type parameter T in angle brackets.
public class GenericList<T>
{
    // The nested class is also generic, and
    // holds a data item of type T.
    private class Node(T t)
    {
        // T as property type.
        public T Data { get; set; } = t;

        public Node? Next { get; set; }
    }

    // First item in the linked list
    private Node? head;

    // T as parameter type.
    public void AddHead(T t)
    {
        Node n = new(t);
        n.Next = head;
        head = n;
    }

    // T in method return type.
    public IEnumerator<T> GetEnumerator()
    {
        Node? current = head;

        while (current is not null)
        {
            yield return current.Data;
            current = current.Next;
        }
    }
}


I want to implement a linkedList by scratch in C#. Why not just use a class of "Node" or "LinkedList" ? why we should have both, what if we don't have them?
Was this page helpful?