Nesting Classes in C#

 

If one class contains another class within it is called Nesting Classes. For example a Button class might have a member of type Location, and a Location class might contain members of type Point. Finally, Point might contain members of type int.

 

Today we discuss about nesting classes in C# with an example. If ClassA contains ClassB within it, ClassB is called nested class and ClassA is called outer class. ClassB can act as a helper class for ClassA. The scope of the nested class is within the outer class and nested class has the access of all members in the outer class even the members are private.

 

namespace CSharpNestingClasses

{

    public class OuterCls

    {

        public string Display()

        {

            return "This is from Outer Class";

        }

 

        public class NestedCls

        {

            public string Display()

            {

                return "This is from Nested Class";

            }

        }

    }

}

 

As shown above we have OuterCls as outer class; it contains one method and one class NestedCls as nested class. The nested class also contains one method. Now we will call the outer class method as well as nested class method.

 

using System;


namespace CSharpNestingClasses

{

    class Program

    {

        static void Main(string[] args)

        {

            OuterCls objOuter = new OuterCls();

            Console.WriteLine(objOuter.Display());

 

            OuterCls.NestedCls objNested = new OuterCls.NestedCls();

            Console.WriteLine(objNested.Display());

 

            Console.ReadLine();

        }

    }

}

 

As shown above by creating the object for outer class OuterCls we are calling the outer class method. To call the nested class method we have to create the object for nested class. We have to access nested class with the help of outer class like OuterClass.NestedClass(here OuterCls.NestedCls). That means outer class behaves like namespace to access nested class. The output is as shown below.

 

                                   

                                                                                                              CSharpNestingClasses.zip (23.91 kb)