Nested Types in C# - SQL Programmers

Nested Types in C#

10/05/2010

A class or a struct defined inside another class or struct is called a nested type. In the following example the Employee class is defined inside the Company class.

namespace Examples
{
    class Company
    {
        class Employee
        {
            public string str = "Nest Class Example.";
        }

        public static void Main()
        {
            Employee objEmployee = new Employee();
            Console.WriteLine(objEmployee.str);
        }
    }
}

We can create an object for Employee class. After that we print the variable which is defined inside the Employee class.  Here the Employee class is an inner class. If the inner class is out side the main class then we have to create an object for that differently.

Example

namespace Examples
{
    class Company
    {
        class Employee
        {
            public string str = "A string variable in nested class";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee x = new Employee();
        }
    }
}

Result

When you compile the above program you will get the following error.

“The type or namespace name 'Employee' could not be found (are you missing a using directive or an assembly reference?)”

The Employee is the inner class which resides inside the base class Company. But the company class is outside the class “Program”. You cannot directly create an object for the class Employee

Example

namespace Examples
{
    class Company
    {
        public class Employee
        {
            public void display()
            {
                Console.WriteLine("From Inner Class");
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Company.Employee x = new Company.Employee();
            x.display();
        }
    }
}

The above program will print “From Inner Class”. Here we created an object for the  inner class Employee like

Company.Employee x = new Company.Employee();

There is another way to run the above example with some modifications. See the following example

namespace Examples
{
    class Company
    {
        public void callMethod()
        {
            Employee emp = new Employee();
            emp.display();
        }
        public class Employee
        {
            public void display()
            {
                Console.WriteLine("From Inner Class");
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Company x = new Company();
            x.callMethod();
        }
    }
}

We defined a new method callMethod() inside the class Company, created an object for the class “Company”, then invoked the method callMethod(). Inside the callMethod() we created an object for the Inner Class Employee and called the method display(). Hence we get the result “From Inner Class”.