
What is a nested class? And when should you use nested classes in your C# programs? Nested classes refer to class declarations that occur in other class declarations.
This C# example program shows how to use nested classes. It explains the concept of nesting.
The class B here is enclosed inside the declaration of class A. Class B is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class A's scope. In the main entry point, we create an instance of A, and also an instance of A.B. The instance of A does not contain an instance of B; the reverse is also the case.
Program that shows nested class B [C#]
class A
{
public int _v1;
public class B
{
public int _v2;
}
}
class Program
{
static void Main()
{
A a = new A();
a._v1++;
A.B ab = new A.B();
ab._v2++;
}
}Types versus instances. The important point about nested classes is that you are declaring types, not member fields. It happens to be possible to enclose one type declaration in another, but they do not merge into the same type.
Type Versus Instance
If you want to merge two types into one type, it is best to use inheritance. If you had class B inherit from class A, class B would have both the _v1 and _v2 fields available. Derived classes are not nested classes; derivation doesn't involve the textual position of classes but rather their runtime characteristics.
You can have one class instance be stored inside another class. Simply add a member field of the class type to the class you want to store it. This is also not a nested class, but simply a member field. This approach can be more useful than inheritance when the classes are not conceptually related.

We explored the conceptual of nested classes in the C# language. Nested classes are determined by the lexical position of the type declarations. Nesting does impact accessibility domains of the nested class as well. Instead of nesting, you can consider inheritance or member fields.
Class Examples