C# Nested Types
In this chapter you will learn:
- What are C# Nested Types
- Example for Nested Types
- Note for Nested Types
- Accessing a private member of a type from a nested type
- Applying the protected access modifier to a nested type
- 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:
- What are Static Classes
- Note for static class
- Example for C# Static Classes
- How to use static class to create utility class