Nested Types

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 has the following features:

  • It can access the enclosing type’s private members and everything else the enclosing type can access.

  • It can be declared with the full range of access modifiers, rather than just public and internal.

  • The default visibility 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 (like when accessing static members).

For example, to access Color.Red from outside our TopLevel class, we’d have to do this:

TopLevel.Color color = TopLevel.Color.Red;

All types can be nested; however, only classes and structs can nest.

Get C# 4.0 Pocket Reference, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.