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. Nested types are used heavily by the compiler itself, when it generates private classes that capture state for constructs such as iterators and anonymous methods.

Note

If the sole reason for using a nested type is to avoid cluttering a namespace with too many types, consider using a nested namespace instead. A nested type should be used because of its stronger access control restrictions, or when the nested class must access private members of the containing class.

Get C# 3.0 Pocket Reference, 2nd 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.