;

C# Nested Class


In C#, a nested class is a class that is defined within another class. Nested classes are useful when you want to logically group classes that are only used in one place or when you want to hide a class from other parts of your program except for the enclosing class. Nested classes can access private members of the outer class, which makes them useful in scenarios where tightly-coupled functionality is needed.

In this tutorial, we will explore the concept of nested classes, their use cases, and how they can be applied in C# programming.

What is a Nested Class?

A nested class is a class defined within the scope of another class. Nested classes are useful for representing hierarchical relationships between classes or when a class is only relevant in the context of its containing (outer) class. Nested classes have access to all members of the outer class, including private members, which allows for a tightly integrated relationship between the outer and nested class.

Key Characteristics:

  • Nested classes can be private, public, protected, internal, or protected internal.
  • A nested class can access the private, protected, and public members of the outer class.
  • An outer class cannot access the members of a nested class unless the members are public.
  • Nested classes are not commonly used in everyday programming, but they are helpful in specific scenarios.

Example Structure of a Nested Class

class OuterClass
{
    private int outerField = 100;

    class NestedClass
    {
        public void DisplayOuterField(OuterClass outer)
        {
            // Access private member of the outer class
            Console.WriteLine(outer.outerField);
        }
    }
}

In this example, the NestedClass has access to the outerField of the OuterClass, even though outerField is private.

Types of Nested Classes

Nested classes can have various access modifiers, which determine their visibility from outside the outer class. Here's a quick overview of the types of nested classes:

  • Private Nested Class: This class is accessible only within the outer class.
  • Public Nested Class: This class is accessible from any part of the program, but still, it needs to be accessed through the outer class.
  • Protected Nested Class: This class is accessible within the outer class and derived classes.
  • Internal Nested Class: This class is accessible only within the same assembly.
  • Protected Internal Nested Class: This class is accessible within the same assembly or from derived classes.

Examples of Nested Classes

Let's look at a few examples to understand how nested classes work in C#.

Example 1: Private Nested Class

class OuterClass
{
    private int outerField = 42;

    private class NestedClass
    {
        public void ShowOuterField(OuterClass outer)
        {
            Console.WriteLine("Outer field value: " + outer.outerField);
        }
    }

    public void CallNestedClass()
    {
        NestedClass nested = new NestedClass();
        nested.ShowOuterField(this);
    }
}

In this example, NestedClass is private, so it can only be used within OuterClass. The method CallNestedClass creates an instance of NestedClass and calls the method ShowOuterField.

Usage:

OuterClass outer = new OuterClass();
outer.CallNestedClass(); // Output: Outer field value: 42

Example 2: Public Nested Class

class OuterClass
{
    private int outerField = 50;

    public class NestedClass
    {
        public void AccessOuterField(OuterClass outer)
        {
            Console.WriteLine("Accessing outer field: " + outer.outerField);
        }
    }
}

In this example, NestedClass is public, so it can be accessed from outside the OuterClass.

Usage:

OuterClass outer = new OuterClass();
OuterClass.NestedClass nested = new OuterClass.NestedClass();
nested.AccessOuterField(outer); // Output: Accessing outer field: 50

Example 3: Protected Nested Class

class OuterClass
{
    protected int outerField = 100;

    protected class NestedClass
    {
        public void DisplayOuterField(OuterClass outer)
        {
            Console.WriteLine("Outer field: " + outer.outerField);
        }
    }
}

class DerivedClass : OuterClass
{
    public void UseNestedClass()
    {
        NestedClass nested = new NestedClass();
        nested.DisplayOuterField(this);
    }
}

In this example, the nested class is protected and can be accessed from the DerivedClass.

Real-World Example

Example: Managing Hierarchical Structures

A good real-world scenario for nested classes is managing hierarchical structures. For example, you might want to implement an organizational structure where each department has employees. A nested class could be used to represent the relationship between departments and employees.

class Department
{
    private string departmentName;

    public Department(string name)
    {
        departmentName = name;
    }

    public class Employee
    {
        public string EmployeeName { get; set; }

        public Employee(string name)
        {
            EmployeeName = name;
        }

        public void ShowDetails(Department dept)
        {
            Console.WriteLine($"Employee {EmployeeName} works in {dept.departmentName} department.");
        }
    }
}

In this example, the Employee class is nested inside the Department class. The Employee class can access the private departmentName field of the Department class.

Usage:

Department department = new Department("HR");
Department.Employee employee = new Department.Employee("John");
employee.ShowDetails(department); // Output: Employee John works in HR department.

This setup allows for logically grouping the Employee class inside the Department class and establishing a tight relationship between the two.

Key Takeaways

  1. Tight Coupling: Nested classes allow for tight coupling between the outer class and the nested class, especially when the nested class needs access to the outer class's private members.
  2. Logical Grouping: Nested classes are useful for logically grouping related classes that are only relevant within the context of the outer class.
  3. Access Modifiers: You can control the visibility of the nested class using access modifiers like private, public, protected, etc.
  4. Real-World Usage: Nested classes are particularly useful for representing hierarchical relationships, such as employees in departments or other structures where one entity is strongly related to another.
  5. Visibility Scope: Outer classes have control over how nested classes are accessed from outside, and nested classes can access the outer class's members, providing flexibility in design.

Summary

C# nested classes provide a way to encapsulate and tightly couple functionality that only makes sense within the context of another class. They can access the members of their enclosing class, which allows for highly cohesive relationships between classes. Nested classes are not commonly used, but they are powerful in specific use cases such as utility classes within larger structures, organizing complex hierarchical models, or providing helper functionality that should not be accessed by other parts of the program.

By understanding how and when to use nested classes, you can design more modular, efficient, and organized code that accurately represents hierarchical structures or encapsulated behavior. Nested classes are a key tool for maintaining tight relationships within an outer class while controlling accessibility and visibility in your program.