C# Nested Types

Description

A nested type is declared within the scope of another type.

Example

For example:


public class TopLevel
{/*from  w  ww  . ja v a 2 s  .co m*/
  public class Nested { }               // Nested class
  public enum Color { Red, Blue, Tan }  // Nested enum
}

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

For example,

TopLevel.Color color = TopLevel.Color.Red;

Note

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 visibility for a nested type is private rather than internal.

Example 2

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


public class TopLevel
{/*from  ww  w. j  a  v  a 2s . c o m*/
  static int x;
  class Nested
  {
    static void Foo() { Console.WriteLine (TopLevel.x); }
  }
}

Example 3

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


public class TopLevel
{/*from w w w .j a  v  a2  s .c  om*/
  protected class Nested { }
}
public class SubTopLevel : TopLevel
{

  static void Foo() { new TopLevel.Nested(); }

}

Example 4

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


public class TopLevel {
  public class Nested { }
}//from w  w w. ja va 2 s .  c om

class Test {
  TopLevel.Nested n;
}




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor