Loading...

Nested Classes in C#

Nested Class in C#:


Nested Class is Class inside a Class, same as nested loop which is loop inside a loop. Nested Class are by default Private, but can be made public, protected, internal and internal protected.

Example:


class Human
    {
        public Human()
        {
            Console.WriteLine("Human");  // Constructor of Human Class
        }

      public  class Student   // Nested or Inner class in Human class
        {
            public Student()  // Constructor of Student Class
            {
                Console.WriteLine("Student");
            }
        }
    }
  
    class Program
    {
        static void Main(string[] args)
        {
            Human h = new Human();  // Object of Human Class
            Human.Student s = new Human.Student(); // Making Object of Nested Class
        }
    }

Output of Nested Class:


 Reasons to Use Nested Class:

     We use nested classes due to following Reasons:
  • By using Nested Classes to nest small classes in large one can make code more readable and maintainable.
  • Nested Classes is used to group all classes together that are useful to only that class, it make package Streamlined.
  • Nested Classes Increase Encapsulation and if you declare the inner class "private" then you can hide the inner class from all other classes and outside world.
Remember that over use of nested classes can make your code more difficult and maintain.

Thank You for Reading, Like it if you understood, It helps a lot to keep us motivated

Google+

 
TOP