C# Nested Class

In C#, a class can be defined within another class, which is called a nested class. A nested class can be private or protected, which means it is only accessible from the containing class or from derived classes.

Why use nested classes?

Nested classes are useful when a class has a close relationship with another class and is not useful outside of that relationship. By making it a nested class, you can encapsulate it within the parent class and make it easier to manage.

Syntax

The syntax for defining a nested class is similar to that of a regular class, but with an additional keyword:

1class OuterClass 2{ 3 // ... 4 class NestedClass 5 { 6 // ... 7 } 8}

Accessing a nested class

To access a nested class, you need to qualify its name with the name of the containing class:

1OuterClass.NestedClass nestedObj = new OuterClass.NestedClass();

Example

Here is an example of a nested class:

1using System; 2 3public class Program 4{ 5 class Calculator 6 { 7 public int Add(int x, int y) 8 { 9 return x + y; 10 } 11 12 public int Subtract(int x, int y) 13 { 14 return x - y; 15 } 16 17 public class ScientificCalculator 18 { 19 public double Power(int x, int y) 20 { 21 return Math.Pow(x, y); 22 } 23 } 24 } 25 26 public static void Main() 27 { 28 Calculator.ScientificCalculator sciCalc = new Calculator.ScientificCalculator(); 29 double result = sciCalc.Power(2, 3); 30 Console.WriteLine("2 to the power of 3 is " + result); 31 } 32}

In this example, the Calculator class has a nested ScientificCalculator class. We create an instance of ScientificCalculator and use it to calculate the power of 2 to 3.