Tuesday, December 4, 2018

What is a nested class? And when should you use nested classes in your C# programs?

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.

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

Example:

class A
{
    public int _v1;

    public class B============nested classs
    {
        public int _v2;
    }
}

class Program
{
    static void Main()
    {
        A a = new A();
        a._v1++;

        A.B ab = new A.B();
        ab._v2++;
    }
}

Note: The main feature of nested classes is that they can access private members of the outer class while having the full power of a class itself. Also they can be private which allows for some pretty powerful encapsulation in certain circumstances:\

  • A nested class can be declared as a private, public, protected, internal, protected internal, or private protected.
  • Outer class is not allowed to access inner class members directly as shown in above example.
  • You are allowed to create objects of inner class in outer class.
  • Inner class can access static member declared in outer class as shown in the below example:
  • Inner class can access non-static member declared in outer class as shown in the below example:

No comments:

Post a Comment