Click here to Skip to main content
15,881,173 members
Articles / Programming Languages / C#
Article

A Tutorial on Nested Classes in C#

Rate me:
Please Sign up or sign in to vote.
3.16/5 (48 votes)
25 Sep 20076 min read 317.9K   42   35
A tutorial meant to be a begginers tutorial to nested classes in C#

Introduction

In this short tutorial we are going to discuss nested classes. Nested classes are classes within classes. Let us try and understand better by writing simple programs.

P1.cs

C#
class OurOuterClass
{
    public static void Main()
    {
        System.Console.WriteLine("OurOuterClass");
    } 
}

Output

OurOuterClass

The above program compiles and runs successfully to give the desired output. The above program consists of one single class named OurOuterClass. OK! So let's try another class within OurOuterClass.

P2.cs

C#
class OurOuterClass
{
    public static void Main()
    {
        System.Console.WriteLine("OurOuterClass");
    }

    class OurNestedClass
    {

    } 
}

Output

OurOuterClass

The above program compiles and runs successfully to give the desired output. The above program consists of one single class named OurOuterClass. Not only that! OurOuterClass contains OurNestedClass within it. That's the nested class.

Let's understand how a nested class looks through one more example.

P3.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("DemoClass");
    }
}

class OuterClass
{
    class NestedClass
    {

    }
}

Output

DemoClass

The above program compiles and runs successfully to give the desired output. The above program consists of three classes: the Demo class that consists of the Main method, the outer class named OuterClass, and the nested Class named NestedClass within the outer class.

Now let's explore the nested classes. Can we create an object of NestedClass from within the Demo class? Let's find out.

P4.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("DemoClass");
        NestedClass obj = new NestedClass();
    }
}

class OuterClass
{
    class NestedClass
    {

    }
}

Output

P4.cs(6,7): error CS0246: The type or namespace name 'NestedClass' could not 
be found (are you missing a using directive or an assembly reference?)

P4.cs(6,29): error CS0246: The type or namespace name 'NestedClass' could not 
be found (are you missing a using directive or an assembly reference?)

Error! That's because the Demo class is not allowed to use the class NestedClass directly as it is contained within the class OuterClass. OK! So can we create an object of NestedClass from within the OuterClass? Let's find out.

P5.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("DemoClass");
    }
}

class OuterClass
{
    class NestedClass
    {

    }
    public void CreateObjectOfNestedClass()
    {
        NestedClass obj = new NestedClass();
    }
}

Output

DemoClass

The above program compiles and runs successfully to give the desired output. The above program shows that we can create an object of NestedClass from within the OuterClass. In the above program we have defined a new method CreateObjectOfNestedClass() within the OuterClass. Inside this method we have created the object of NestedClass.

What if we want to get a reference to a NestedClass object obj from within the Demo class? Well, we need to modify the function CreateObjectOfNestedClass() to return an object of type NestedClass. Then in the Main() block of the Demo class, we need to create an object of OuterClass. Then we need to invoke the function CreateObjectOfNestedClass() using the object from OuterClass. The CreateObjectOfNestedClass() returns the object obj of NestedClass. We catch this object in the reference of type NestedClass, created in the Main() block of the Demo class. This is what the following program does:

P6.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("DemoClass");

        OuterClass oc = new OuterClass();
        NestedClass reference = oc.CreateObjectOfNestedClass();
    }
}

class OuterClass
{
    class NestedClass
    {

    }
    public void CreateObjectOfNestedClass()
    {
        NestedClass obj = new NestedClass();
        return obj;
    }
}

Output

P6.cs(9,7): error CS0246: The type or namespace name 'NestedClass' could not 
be found (are you missing a using directive or an assembly reference?)

Error! We did everything according to our initial plan. Then where did we fail? Well we failed at line 9 where we are referencing the nested class directly from Main() in the Demo class. Didn't we learn from programs P3.cs and P4.cs that the Demo class is not allowed to use NestedClass directly, as it is contained within the OuterClass? Certainly we did. So what's the solution to this problem? We need to know the right way to reference the NestedClass from Main() inside Demo. Well we need to use the fully qualified name for NestedClass within Main() in the Demo class, which is done with the following program.

P7.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("DemoClass");

        OuterClass oc = new OuterClass();
        OuterClass.NestedClass reference = oc.CreateObjectOfNestedClass();
    }
}

class OuterClass
{
    class NestedClass
    {

    }
    public NestedClass CreateObjectOfNestedClass()
    {
        NestedClass obj = new NestedClass();
        return obj;
    }
}

Output

P7.cs(19,23): error CS0050: Inconsistent accessibility: return type 
'OuterClass.NestedClass' is less accessible than method 
'OuterClass.CreateObjectOfNestedClass()'

P7.cs(15,10): (Location of symbol related to previous error)

Error again! Now where did we go wrong? The compiler error tells us that we need to make the class NestedClass public.

P8.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("DemoClass");

        OuterClass oc = new OuterClass();
        OuterClass.NestedClass reference = oc.CreateObjectOfNestedClass();
    }
}

class OuterClass
{
    public class NestedClass
    {

    }
    public NestedClass CreateObjectOfNestedClass()
    {
        NestedClass obj = new NestedClass();
        return obj;
    }
}

Output

DemoClass

Bingo! The above program compiles and runs successfully to give the desired output. We know that we can reference the NestedClass from Main() in Demo by using its fully qualified name, and making the NestedClass public. Then can we do away with the extra headache of creating object oc of OuterClass and invoking oc.CreateObjectOfNestedClass()? Yes, certainly we can get rid of this headache. We can get rid of CreateObjectOfNestedClass() defined within the NestedClass class. This is how we do so.

P9.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("DemoClass");
        OuterClass.NestedClass reference = new OuterClass.NestedClass();
    }
}

class OuterClass
{
    public class NestedClass
    {

    }
}

Output

DemoClass

The above program compiles and runs successfully to give the desired output. Wasn't that simple?

Nested Classes and Static Members

Let us see how nested classes behave with the static members.

P10.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine(OuterClass.NestedClass.x);     
    }
}

class OuterClass
{
    public class NestedClass
    {
        public static int x = 100;
    }
}

Output

100

The instance class is not required to access static variables. The rules that apply to standalone classes in case of static variables also apply to nested classes. For nested classes, fully qualified names of nested classes must be used to access the static variables as shown by the above program.

Nested Classes and Members in Containers

Let us see how nested classes behave with the members in containing classes.

P11.cs

C#
class Demo
{
  public static void Main()
  {
      System.Console.WriteLine("Demo");     
  }
}
 
class OuterClass
{
   public int y = 100;
 
   public class NestedClass
   {
      public void abc()
      {
          System.Console.WriteLine(y);     
      }
   }
}

Output

P11.cs(17,35): error CS0038: Cannot access a nonstatic member of outer type

'OuterClass' via nested type 'OuterClass.NestedClass'

Error! That's because the NestedClass cannot access the non-static, member y declared in the OuterClass. The members of the OuterClass are not directly available to the NestedClass. Well, then how can the NestedClass access the members of the containing class? This is how:

P12.cs

C#
class Demo
{
  public static void Main()
  {
      System.Console.WriteLine("Demo");
      OuterClass.NestedClass.abc();     
  }
}
 
class OuterClass
{
   public static int y = 100;
 
   public class NestedClass
   {
      public static void abc()
      {
              System.Console.WriteLine(OuterClass.y);     
      }
   }
}

Output

Demo

100

The above program compiles and runs successfully to give the desired output. NestedClass can access static member y declared in the OuterClass. Declaring a member as static in the OuterClass makes it directly available in the NestedClass.

It is not always necessary to declare an outer class member as static to make it directly available in the nested class. There is one more way by which the nested class can directly access non-static members of the container class. This is how:

P13.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("Demo");
        OuterClass.NestedClass.abc();     
    }
}

class OuterClass
{
    public int y = 100;

    public class NestedClass
    {
        public static void abc()
        {
            OuterClass oc = new OuterClass();
            System.Console.WriteLine(oc.y);     
        }
    }
}

Output

Demo

100

The above program compiles and runs successfully to give the desired output. The NestedClass can access the non static members of the container class via objects created in the nested class. In the above program the function abc() is a member of the nested class. Inside the function abc() we have created the object of the outer class and then we are accessing the non static member y of the OuterClass.

Constructors and Nested Classes

Let us try to understand (through small examples) how constructors in outer and nested classes behave.

P14.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("Demo");
        OuterClass oc = new OuterClass();    
    }
}

class OuterClass
{
    public OuterClass()
    {
        System.Console.WriteLine("OuterClass");     
    }

    public class NestedClass
    {
        public NestedClass()
        {
            System.Console.WriteLine("NestedClass");     
        }
    }
}

Output

Demo

OuterClass

The above program compiles and runs successfully to give the desired output. An attempt was made to create an object of OuterClass. Therefore the constructor of OuterClass got executed. There is no reason why the constructor of NestedClass should get executed.

P15.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("Demo");
        OuterClass.NestedClass nc = new OuterClass.NestedClass();    
    }
}

class OuterClass
{
    public OuterClass()
    {
        System.Console.WriteLine("OuterClass");     
    }

    public class NestedClass
    {
        public NestedClass()
        {
            System.Console.WriteLine("NestedClass");     
        }
    }
}

Output

Demo

NestedClass

The above program compiles and runs successfully to give the desired output. An attempt was made to create an object of NestedClass. Therefore the constructor of NestedClass got executed. There is no reason why the constructor of OuterClass should get executed.

Inheritance and Nested Classes

We can inherit classes that have already inherited classes. This is how:

P16.cs

C#
class OuterClass
{
    public OuterClass()
    {
        System.Console.WriteLine("OuterClass");     
    }

    public class NestedClass
    {
        public NestedClass()
        {
            System.Console.WriteLine("NestedClass");     
        }
    }
}

class Demo : OuterClass
{
    public static void Main()
    {
        Demo dc = new Demo();    
        System.Console.WriteLine("Demo");
    }
}

Output

OuterClass

Demo

The above program compiles and runs successfully to give the desired output. The base class constructor gets executed first and then the derived class's constructor gets executed.

A final question: can we have a NestedClass inheriting from the OuterClass? Well yes! Check it out.

P17.cs

C#
class Demo
{
    public static void Main()
    {
        System.Console.WriteLine("Demo");
        OuterClass.NestedClass.abc();     
    }
}

class OuterClass
{
    private int y = 100;

public class NestedClass : OuterClass
{
    public static void abc()
    {
        OuterClass oc = new OuterClass();
        System.Console.WriteLine(oc.y);     
    }
}
}

Output

Demo

100

The above program compiles and runs successfully to give the desired output. It is perfectly fine to have a nested class that is derived from the outer class.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
India India
I am a Software engineer with around 7+ years of experience. Most of my experience is in Storage technology.

Comments and Discussions

 
QuestionVery good article! There are some things that I wanna add Pin
The_Unknown_Member18-Mar-18 2:30
The_Unknown_Member18-Mar-18 2:30 
QuestionPeople knocked this article, but it gave me what I needed Pin
michaelbuie3-Apr-17 9:50
michaelbuie3-Apr-17 9:50 
QuestionThank you... Pin
User-1163031312-Jun-16 22:01
User-1163031312-Jun-16 22:01 
Generalthank you!! Pin
El Kuxidaica20-Jul-15 17:32
El Kuxidaica20-Jul-15 17:32 
GeneralMy 5... Pin
Atul Khanduri9-Mar-14 0:19
Atul Khanduri9-Mar-14 0:19 
Too good for beginner... Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:

I am surprised why some people rate 1 or 2 or 3....
Generalmy 4 Pin
Omar Gameel Salem8-Mar-14 13:47
professionalOmar Gameel Salem8-Mar-14 13:47 
Questionwhat's the use of it? Pin
shamimkeshani23-Nov-13 23:35
shamimkeshani23-Nov-13 23:35 
QuestionRe: what's the use of it? Pin
stixoffire24-Jan-14 11:38
stixoffire24-Jan-14 11:38 
AnswerRe: what's the use of it? Pin
Chetan Kudalkar24-Jan-14 18:10
Chetan Kudalkar24-Jan-14 18:10 
QuestionIts perfect explanation Pin
Mohammed Hameed24-Jan-13 0:30
professionalMohammed Hameed24-Jan-13 0:30 
QuestionThe Plus Sign is used in nHibernate; the dollar sign is used in jHibernate Pin
realbart10-Sep-12 4:44
realbart10-Sep-12 4:44 
QuestionIn the Outer class declare a static field of type InnerClass Pin
APetrut17-May-12 2:32
APetrut17-May-12 2:32 
QuestionMessage Closed Pin
9-Mar-12 20:42
sangram3609-Mar-12 20:42 
QuestionDoubt in nested member Pin
satheesh_k_bu18-Dec-11 17:22
satheesh_k_bu18-Dec-11 17:22 
AnswerRe: Doubt in nested member Pin
Chetan Kudalkar13-Jan-12 4:30
Chetan Kudalkar13-Jan-12 4:30 
GeneralP9.cs How the C# creates inner class instance without creating instance of external class. outer class is not static. but still using as outerclass.innerclass Pin
mvkotekar12-Sep-10 20:55
mvkotekar12-Sep-10 20:55 
GeneralRe: P9.cs How the C# creates inner class instance without creating instance of external class. outer class is not static. but still using as outerclass.innerclass Pin
Aaman00726-Mar-11 7:01
Aaman00726-Mar-11 7:01 
GeneralRe: P9.cs How the C# creates inner class instance without creating instance of external class. outer class is not static. but still using as outerclass.innerclass Pin
smikeshnet28-Apr-11 22:08
smikeshnet28-Apr-11 22:08 
GeneralRe: P9.cs How the C# creates inner class instance without creating instance of external class. outer class is not static. but still using as outerclass.innerclass Pin
Aaman00729-Apr-11 0:28
Aaman00729-Apr-11 0:28 
AnswerRe: P9.cs How the C# creates inner class instance without creating instance of external class. outer class is not static. but still using as outerclass.innerclass Pin
Omar Gameel Salem8-Mar-14 13:31
professionalOmar Gameel Salem8-Mar-14 13:31 
GeneralError in P11.cs Pin
Khaniya28-Mar-10 19:30
professionalKhaniya28-Mar-10 19:30 
GeneralMy vote of 2 Pin
Mohamed Sadek Rady20-Mar-10 12:14
Mohamed Sadek Rady20-Mar-10 12:14 
GeneralRe: My vote of 2 Pin
Khaniya28-Mar-10 19:09
professionalKhaniya28-Mar-10 19:09 
Generalquery on P17.cs Pin
Chintan.Desai14-Jul-09 0:03
Chintan.Desai14-Jul-09 0:03 
GeneralRe: query on P17.cs Pin
Aaman00726-Mar-11 7:29
Aaman00726-Mar-11 7:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.