Embedded types in C#

An embedded type in C# is declared within the scope of another type.

public class FirstLevel
{
  public class NestedClass {} // embedded Class
  public enum Color {Red, Blue, Tan} // Embedded Enum
}

An embedded type has the following features:
1. The embedded type can access the private members of enclosing type and all other types that the enclosing type has access to.
2. The embedded type can have all possible access modifiers and is not limited to public and internal.
3. The default visibility for an embedded type is private and not internal.
4. Access to an embedded type from outside the enclosing type requires a qualification by the name of the enclosing type (such as when accessing static members).

For example, to access Color.Red from outside our FirstLevel class, we would write the following:

 FirstLevel.Color color = FirstLevel.Color.Red;

All types can be embedded within classes and structs. Embedded types are intensively used by the compiler itself, it generates private classes that manage the state in constructs such as iterators and anonymous methods.

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.