Nested Class In C#

Rajnilari2015
Posted by in C# category on for Beginner level | Points: 250 | Views : 1235 red flag
Rating: 5 out of 5  
 1 vote(s)

A class within another class declaration is a Nested class. In this article we will see the nested classes example - how to create them, the purpose of nested class in C#.


 Download source code for Nested Class In C#

Introduction

A class within another class declaration is a Nested class.In this article we will discuss about the nested classes, how to create them, the purpose of them in C#.

What is a nested class

As mentioned, a class that is declared within another class is a nested class. Let us see the nested class example. E.g.

using System;
namespace ConsoleApplication1
{

    class OuterClass
    {
        public void SayHelloFromOuterClass()
        {
            Console.WriteLine("Hello from Outer Class");
        }

        public class InnerClass
        {
            public void SayHelloFromInnerClass()
            {
                Console.WriteLine("Hello from Inner Class");
            }
        }
    }
}

In the above example, we have declared two classes viz. OuterClass and InnerClass. In this case, the InnerClass is declared within the OuterClass. So it is enclosed/nested and hence becomes a Nested class.

Viewing through IL Disassembler(IL DASM) yields

How to instantiate a nested class?

Now suppose we have declared a nested class. The next step is to instantiate it. If we try something as under

static void Main(string[] args)
{
    var innerClass = new InnerClass();
}

The compiler reports

It is quite obvious that, the compiler failed to infer the type of InnerClass() since it is embedded within the OuterClass.So the way to instantiate a nested class is to first instantiate the OuterClass followed by the InnerClass as shown below

static void Main(string[] args)
{               
    var innerClass = new OuterClass.InnerClass();
}

This highlights the concepts of encapsulation.

How to invoke the members of a nested class?

Now to invoke the members of the "Inner Class", we have to put the conventional dot(.) operator and access it's members

static void Main(string[] args)
{               
    var innerClass = new OuterClass.InnerClass();
    innerClass.SayHelloFromInnerClass();
}

Usage of Nested Class

Now let's see some of the practical usage of nested class

1. Encapsulation

We have already seen one above.Below is another way of providing encapsulation using nested class

namespace ConsoleApplication1
{
    public sealed class Singleton
    {
        private static Singleton instance = null;
        private static readonly object lockObj = new object();

        Singleton(){} //private constructor

        public static Singleton Instance
        {
            get
            {
                lock (lockObj)
                {
                    if (System.Object.ReferenceEquals(instance, null))
                    {
                        instance = Inner.Instance;
                    }
                    return instance;
                }
            }
        }

        class Inner
        {            
            Inner(){ }//private constructor
           
            public static Singleton Instance
            {
                get
                {
                    return new Singleton();
                }
            }
        }
    }
}

As can be figure out that the object instantiation is happening only within the inner class which is completely encapsulated.

2. Class Clusters pattern

Class Cluster is a construct that supports implementing the abstract Factory pattern.It provides a Factory (Cluster) interface that manufactures and returns a specific concrete instance of a Factory Object.This factory object then satisfies the behavior of the cluster family as described by the Factory (Cluster) interface.Let us consider another example

abstract public class Animal
{
    private Animal() { }

    private sealed class Tiger : Animal { ... }
    public static Animal MakeTiger() { return new Tiger(); }

    private sealed class Lion : Animal { ... }
    public static Animal MakeLion() { return new Lion(); }

    ......................
    ......................
}

Here Animal is a factory for various types of animals, all of which can use the private implementation details of Animal.But no third party can extend Animal because though a derived class should be able to call a constructor, but all the constructors are private.

3. Partial Class

It is a way of logically grouping classes that are only used in one place.And each class should be dedicated of doing their own action which leads to Single Responsibility Principal (SRP)

4. More readable and maintainable code.

Reference

Nested Types (C# Programming Guide)

Conclusion

Hope this article will serve as a good reference for those who are new to Nested Class concepts in C#. Thanks for reading. Zipped file attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Posted by: Raja on: 12/4/2015 | Points: 25
Thanks Raj, awesome explanations.

The instantiation of nested class was new to me, I thought we can instantiate just with the class name of the nested class but because it is inside another class so we need to prefix it with the parent class name.

Thanks again
Regards
Posted by: Rajnilari2015 on: 12/4/2015 | Points: 25
Thanks @Raja

Login to post response

Comment using Facebook(Author doesn't get notification)