Wednesday, March 20, 2019

Nested Classes in C#

Hello all in this post i will explain you how to create class inside class means nested class in programming language.


class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods (member function which defines actions) into a single unit. In C#, a user is allowed to define a class within another class. Such types of classes are known as nested class. This feature enables the user to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code.

Syntax:
class Outer_class {
       // Code..
       class Inner_class {
          // Code.. 
       } 
}

If you create object of above class

Outer_class test=new Outer_class ();
Outer_class.Inner_class test2 = new Outer_class.Inner_class();
In example i am create simple class you can yous according to your requirement.

Important points:
  • 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.

Thank you,
Arjun Walmiki

No comments:

Post a Comment