Nested classes

suggest change

In C#, a nested class (or nested type) is a class declared directly inside the scope of another enclosing class, struct, or interface. Nested classes are frequently used to encapsulate private implementation details, implement iterators or nodes, and structure patterns like the Builder pattern.


1. Syntax and Access Modifiers

Unlike top-level classes—which can only be declared as public or internal—nested classes can take advantage of the full set of C# access modifiers:

Access Modifier Accessibility
private (default) Accessible only within the enclosing type.
protected Accessible within the enclosing type and types derived from it.
internal Accessible anywhere within the same assembly.
protected internal Accessible within the same assembly or derived types in any assembly.
private protected Accessible within the enclosing type and derived types in the same assembly.
public Accessible from any assembly that can access the enclosing class.
public class Container
{
    // Default visibility for nested types is private
    class PrivateWorker
    {
        public void Execute() => Console.WriteLine("Worker running...");
    }

    public class PublicHelper
    {
        public static void HelperMethod() => Console.WriteLine("Helper invoked.");
    }

    public void Run()
    {
        var worker = new PrivateWorker();
        worker.Execute();
    }
}

// Accessing from outside:
Container.PublicHelper.HelperMethod(); // Valid
// Container.PrivateWorker worker = ...; // Compile error: Inaccessible due to protection level

2. Accessing Members of the Enclosing Class

A nested class can access all members of its enclosing class—including private static and instance members.

Key Difference from Java: In C#, a nested class does not hold an implicit reference to an instance of the outer class. To access non-static instance fields of the enclosing class, an instance of the enclosing class must be explicitly passed in.

public class BankAccount
{
    private decimal _balance;
    private readonly string _accountNumber;

    public BankAccount(string accountNumber, decimal initialDeposit)
    {
        _accountNumber = accountNumber;
        _balance = initialDeposit;
    }

    // Nested class has access to private fields of BankAccount
    private class TransactionAuditor
    {
        private readonly BankAccount _account;

        public TransactionAuditor(BankAccount account)
        {
            _account = account; // Explicitly pass enclosing instance
        }

        public void Audit(decimal amount)
        {
            // Accesses private field _balance directly
            Console.WriteLine($"Account {_account._accountNumber} balance is ${_account._balance:N2}");
        }
    }

    public void Deposit(decimal amount)
    {
        _balance += amount;
        new TransactionAuditor(this).Audit(amount);
    }
}

3. Common Design Patterns

1. Private Implementation Details (Data Structures)

Hiding auxiliary data structures (such as tree or linked-list nodes) prevents exposing internal pointers:

public class SimpleLinkedList<T>
{
    // Node is an internal detail that callers never interact with directly
    private class Node
    {
        public T Value { get; }
        public Node? Next { get; set; }

        public Node(T value) => Value = value;
    }

    private Node? _head;

    public void AddFirst(T item)
    {
        var newNode = new Node(item) { Next = _head };
        _head = newNode;
    }
}

2. The Builder Pattern

Public nested classes provide an elegant, discoverable way to construct complex immutable objects:

public class HttpRequestMessageBuilder
{
    public string Url { get; }
    public string Method { get; }
    public TimeSpan Timeout { get; }

    // Private constructor: can only be built via Builder
    private HttpRequestMessageBuilder(Builder builder)
    {
        Url = builder.Url;
        Method = builder.Method;
        Timeout = builder.Timeout;
    }

    public class Builder
    {
        public string Url { get; private set; } = "https://localhost";
        public string Method { get; private set; } = "GET";
        public TimeSpan Timeout { get; private set; } = TimeSpan.FromSeconds(30);

        public Builder WithUrl(string url)
        {
            Url = url;
            return this;
        }

        public Builder WithMethod(string method)
        {
            Method = method;
            return this;
        }

        public Builder WithTimeout(TimeSpan timeout)
        {
            Timeout = timeout;
            return this;
        }

        public HttpRequestMessageBuilder Build() => new HttpRequestMessageBuilder(this);
    }
}

// Usage:
var request = new HttpRequestMessageBuilder.Builder()
    .WithUrl("https://api.example.com/items")
    .WithMethod("POST")
    .Build();

4. Reflection and CLR Type Naming

In the Common Language Runtime (CLR), nested classes are identified using a plus sign (+) rather than a dot (.):

Type nestedType = typeof(Container.PublicHelper);

Console.WriteLine(nestedType.FullName); 
// Output: "MyApp.Container+PublicHelper"

When looking up nested types dynamically via Type.GetType(), always use the + syntax:

Type? t = Type.GetType("MyApp.Container+PublicHelper");

5. Summary and Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents