Nested Types - CSharp Custom Type

CSharp examples for Custom Type:Inner Type

Introduction

A nested type is declared within the scope of another type. For example:

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

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

A nested type can be declared with the full range of access modifiers, rather than just public and internal.

The default accessibility for a nested type is private rather than internal.

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

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:

public class TopLevel
{
  static int x;
  class Nested
  {
    static void Foo() { Console.WriteLine (TopLevel.x); }
  }
}

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

public class TopLevel
{
  protected class Nested { }
}

public class SubTopLevel : TopLevel
{
  static void Foo() { new TopLevel.Nested(); }
}

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

public class TopLevel
{
  public class Nested { }
}

class Test
{
  TopLevel.Nested n;
}

Related Tutorials