Using Nested Class in CSharp




Nested Classes

Using Nested Class in CSharp

The facility of using nested class in csharp is quite critical to understand because it lefts many questions in the minds of the developers when they already know that csharp offers inheritance in a very well manner in the form of modifiers such as public, protected, internal, private etc and also gives us abstraction in the form of abstract classes or other things such as interfaces that just show the things, not their actual working.
Nesting classes or related objects in csharp is just a simple technique. We just want some hidden things inside our class in case, if we have already made an application which is very well running, but we want to make another object/ class that behaves exactly like our class but it is encapsulated within that class. The main reason in doing so, is to restructure some data in the existing class and extend its functionality without going into the complexity of either creating the inherited class.
Let us take another example:
If we want something more from an existing class that cannot be inherited and if changing the access level could bring the disaster to the entire application then what we will do?
Or in another scenario:
The class cannot be inherited but we need some more functionality from that same class and in doing so, we will completely forget about what we have already written inside that class because, there is lots of code in our class.
There comes the concept of using nested class in csharp.
Let us take an example first:

using System;

namespace Using_Nested_Classes
{
// MainClass that contains Nested Class
class MainClass
{

// MainClass Constructor
public MainClass(int a, int b)
{

Console.WriteLine(“====Addition using MainClass====”);
Console.WriteLine(“Enter an integer:”);
a = int.Parse(Console.ReadLine());
Console.WriteLine(“Enter a second integer :”);
b = int.Parse(Console.ReadLine());
int c = a + b;
Console.WriteLine(“Sum of {0} and {1} is {2}”, a, b, c);
Console.ReadKey();

}

// The NestedClass
public class NestedClass
{
//Nested Class Constructor
public NestedClass()
{

Console.WriteLine(“===Addition using Nested Class===”);

}

MainClass objMain = new MainClass(2, 2);

}
}

class Program
{
static void Main(string[] args)
{
MainClass objMain = new MainClass(1,2);
MainClass.NestedClass objNested = new MainClass.NestedClass();

}
}
}

The Output is:

====Addition using MainClass====
Enter an integer:
1
Enter a second integer :
2
Sum of 1 and 2 is 3
====Addition using MainClass====
Enter an integer:
2
Enter a second integer :
2
Sum of 2 and 2 is 4