Nested Classes in C#

CsharpProgrammingServer Side Programming

Nested class is a class declared in another enclosing class. It is a member of its enclosing class and the members of an enclosing class have no access to members of a nested class.

Let us see an example code snippet of nested classes in C# −

Example

class One {
   public int val1;

   public class Two {
      public int val1;
   }
}

class Demo {
   static void Main() {
      One a = new One();
      a.val1++;

      One.Two ab = new One.Two();
      ab.val2++;
   }
}

The example shows that class Two is a nested class. The class Two is enclosed inside the class One declaration.

The class Two here is enclosed inside the declaration of class One. Class Two is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class One's scope.

raja
Published on 14-Aug-2018 12:50:21
Advertisements