C#C
C#12mo ago
87 replies
Faker

✅ Nested classes in C# with parent being a generic class

Hello guys, consider the code in the picture, can someone explain why the type parameters declared in our parent generic class is available in the nested private class please.

Also notice in the following code:
// 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;
        }
    }
}


We declare a private class with parentheses, what does that implies please.
5BCEFC40-F4BF-4F35-B8FF-3891DB407E1E.png
Was this page helpful?