Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Nested Class

This C# example program uses nested classes. It explains the concept of nesting.

Nested class. 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. They are sometimes useful.

Example. 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.

Here: We create an instance of A and an instance of A.B. The instance of A does not contain an instance of B.

C# program that shows nested class B

class A
    public int _v1;

    public class B
	public int _v2;

class Program
    static void Main()
	A a = new A();

	A.B ab = new A.B();

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.

Inheritance. 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.

Note: Derivation doesn't involve the textual position of classes but rather their runtime characteristics.

Also, you can have one class instance be stored inside another class. Simply add a member field of the class type to the class where you want to store it. This is also not a nested class, but simply a member field.

Tip: This approach can be more useful than inheritance when the classes are not conceptually related.

Summary. 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.