Click here to Skip to main content
Click here to Skip to main content

A Tutorial on Nested Classes in C#

, 25 Sep 2007
Rate this:
Please Sign up or sign in to vote.
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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

About the Author

Chetan Kudalkar
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

 
GeneralMy 5... PinmemberAtul Khanduri9-Mar-14 0:19 
Generalmy 4 PinmemberOmar Gameel Salem8-Mar-14 13:47 
Questionwhat's the use of it? Pinmembershamimkeshani23-Nov-13 23:35 
QuestionRe: what's the use of it? Pinmemberstixoffire24-Jan-14 11:38 
AnswerRe: what's the use of it? PinmemberChetan Kudalkar24-Jan-14 18:10 
QuestionIts perfect explanation PinmemberMohammed Hameed24-Jan-13 0:30 
QuestionThe Plus Sign is used in nHibernate; the dollar sign is used in jHibernate Pinmemberrealbart10-Sep-12 4:44 
QuestionIn the Outer class declare a static field of type InnerClass Pinmembermoldo17-May-12 2:32 
QuestionNested Types in c# Pinmembersangram3609-Mar-12 20:42 
QuestionDoubt in nested member [modified] Pinmembersatheesh_k_bu18-Dec-11 17:22 
AnswerRe: Doubt in nested member PinmemberChetan 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 Pinmembermvkotekar12-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 PinmemberAaman00726-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 Pinmembersmikeshnet28-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 PinmemberAaman00729-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 PinmemberOmar Gameel Salem8-Mar-14 13:31 
GeneralError in P11.cs PinmemberKhaniya28-Mar-10 19:30 
GeneralMy vote of 2 PinmemberDr. Sadek M. Rady20-Mar-10 12:14 
GeneralRe: My vote of 2 PinmemberKhaniya28-Mar-10 19:09 
Generalquery on P17.cs PinmemberChintan.Desai14-Jul-09 0:03 
GeneralRe: query on P17.cs PinmemberAaman00726-Mar-11 7:29 
QuestionNested Class Array Definition Pinmembermohammadmdp4-Apr-09 19:46 
AnswerRe: Nested Class Array Definition PingroupChintan.Desai14-Jul-09 0:20 
AnswerRe: Nested Class Array Definition PinmemberAaman00726-Mar-11 6:43 
Generalerror in code Pinmemberforester joe28-Jan-09 23:02 
GeneralInheriting Nested Class's Methods. PinmemberiAmEntity13-Dec-08 6:51 
GeneralPro's and Con's PinmemberKellros18-Sep-08 10:52 
GeneralIntellisense with Nested Classes Pinmembermyklk30-Nov-07 0:02 
GeneralNested Classes are just for visibility PinmemberAndrew Phillips10-Oct-07 19:20 
GeneralMemories from College Pinmemberblackjack215026-Sep-07 2:00 
GeneralRe: Memories from College PinmemberChetan Kudalkar26-Sep-07 2:09 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 25 Sep 2007
Article Copyright 2007 by Chetan Kudalkar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid