CSharp - Type Creation Nested Types

Introduction

A nested type is declared within the another type.

For example:

class OuterType{
       public class Nested { // Nested class
       }               
       public enum Color { // Nested enum
          Red, Blue, Tan 
       }  
}

A nested type can access the enclosing type's private members and everything the enclosing type can access.

A nested type has the full range of access modifiers.

The default access level for a nested type is private.

Accessing a nested type from outside the enclosing type requires qualification with the enclosing type's name.

To access Color.Red from outside our OuterType class, we'd have to do this:

OuterType.Color color = OuterType.Color.Red;

Classes, structs, interfaces, delegates, and enums can be nested inside either a class or a struct.

Here is an example of accessing a private member of a type from a nested type:

class OuterType
{
     static int x;
     class Nested
     {
         static void Test() { 
            Console.WriteLine (OuterType.x); 
         }
     }
}

Here is an example of applying the protected access modifier to a nested type:

class OuterType
{
       protected class Nested { }
}

class SubOuterType : OuterType
{
       static void Test() { new OuterType.Nested(); }
}

Here is an example of referring to a nested type from outside the enclosing type:

class OuterType
{
       public class Nested { }
}

class Test
{
       OuterType.Nested n;
}