C# Nested Types

In this chapter you will learn:

  1. What are C# Nested Types
  2. Example for Nested Types
  3. Note for Nested Types
  4. Accessing a private member of a type from a nested type
  5. Applying the protected access modifier to a nested type
  6. Referring to a nested type from outside the enclosing type

Description

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

Example

For example:


public class TopLevel
{/*w w w  .j  a va 2 s. c  o 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
{// w  w  w  .j  a  va2  s .  co 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
{//ww  w.ja v a  2s .  c  o m
  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. j av a2s  . co  m*/

class Test {
  TopLevel.Nested n;
}

Next chapter...

What you will learn in the next chapter:

  1. What are Static Classes
  2. Note for static class
  3. Example for C# Static Classes
  4. How to use static class to create utility class
Home »
  C# Tutorial »
    C# Types »
      C# Class
C# class
C# Nested Types
C# Static Classes