Saturday, October 26, 2024

Nested classes with example in C#

In C#, a nested class is a class defined within another class. This allows you to logically group related classes and keep them in a single unit. Nested classes have access to the members of the enclosing class, including private members. They can also be static or non-static.

Here's an example of nested classes in C#:

using System;

public class OuterClass
{
    private int outerData;

    public OuterClass(int data)
    {
        outerData = data;
    }

    public void DisplayOuterData()
    {
        Console.WriteLine("Outer data: " + outerData);
    }

    public class NestedClass
    {
        private int nestedData;

        public NestedClass(int data)
        {
            nestedData = data;
        }

        public void DisplayNestedData()
        {
            Console.WriteLine("Nested data: " + nestedData);
        }

        public void AccessOuterData(OuterClass outer)
        {
            Console.WriteLine("Accessing outer data from nested class: " + outer.outerData);
        }
    }
}

public class Program
{
    public static void Main()
    {
        // Creating an instance of the outer class
        OuterClass outer = new OuterClass(10);

        // Creating an instance of the nested class
        OuterClass.NestedClass nested = new OuterClass.NestedClass(20);

        // Accessing and displaying data from the outer and nested classes
        outer.DisplayOuterData();
        nested.DisplayNestedData();

        // Accessing outer data from the nested class
        nested.AccessOuterData(outer);
    }
}
In this example:
  • OuterClass is the outer class that contains the nested class NestedClass.
  • NestedClass is a nested class within OuterClass.
  • NestedClass has access to the private members of OuterClass, such as outerData.
  • The Main method demonstrates creating instances of both the outer and nested classes and accessing their members.

No comments:

Post a Comment

Hot Topics