In this article we are going to discuss the Nested classes in C#. There are many blogs, articles are available on the internet regarding Nested class but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Nested class in C#.
Nested Class Introduction
The following class definition defines a Nested class in C#:
//Nested class
class Outerclass {
// Write Code here
class Innerclass {
// Write Code here
}
}
Real World Example of Nested Class
Consider an example of Car with a music system installed in it. Now this music system’s existence is completely dependent on existence of the Car. This music system can not be used out side the car. The sole purpose of he music system is to serve within the environment of a Car and for that car. So it doesn't really make sense to access this music system outside the context of a Car.
Example
let us understand Nested Class with an example. First, create a console application and then add a class file with the name. Once you add the Nested class and add the following code.
// C# program to illustrate the concept of nested class
using System;
// Outer class
public class Outerclass
{
// Method of outer class
public void method1()
{
Console.WriteLine("Outer class method");
}
// Inner class
public class Innerclass
{
// Method of inner class
public void method2()
{
Console.WriteLine("Inner class Method");
}
}
}
// Driver Class
public class Program
{
// Main method
static public void Main()
{
// Create the instance of outer class
Outerclass obj1 = new Outerclass();
obj1.method1();
// Creating an instance of inner class
Outerclass.Innerclass obj2 =
new Outerclass.Innerclass();
// Accessing the method of inner class
obj2.method2();
}
}
Output
How can Access Private Members of the Outer Class?
The main feature of a nested class can have access to the private members of the outer class, which makes it useful for encapsulation and information hiding. It can also be used to group related functionality together in a single class.
// C# program to illustrate the
// concept of nested class
using System;
// Outer class
public class Outerclass
{
// Method of outer class
private int outerVariable = 20;
// Inner class
public class Innerclass
{
// Method of inner class
public void method2(Outerclass outer)
{
Console.WriteLine("Print outerVariable = "+ outer.outerVariable);
}
}
}
// Driver Class
public class Program
{
// Main method
static public void Main()
{
//Create the instance of outer class
Outerclass obj1 = new Outerclass();
//Creating an instance of inner class
Outerclass.Innerclass obj2 =
new Outerclass.Innerclass();
// Accessing the method of inner class
obj2.method2(obj1);
}
}
Output