Definition - What does Nested Type mean?
Nested type, in C#, is a type declared within an existing class or struct. Unlike a non-nested type, which is declared directly within a compilation unit or a namespace, nested type is defined within the scope of the containing (or outer) type.
Nested type is used only where its scope, visibility and lifetime ends within the containing type without exposing itself to other types. The enumerator member within a collection type is usually implemented as nested type to iterate over the collection. As an iterator, the enumerator enables the use of same client-side logic to iterate the collection, regardless of the data collection's underlying structure.
In general, nested type is used only in situations where it logically belongs to the containing type. It is implemented when the containing type is entirely dependent on the nested type that helps to encapsulate the implementation details of the containing type. It is often used in scenarios where the containing type that has the nested type for its implementation is directly used without any requirement for instantiating its nested type.
Techopedia explains Nested Type
A nested type can be accessed from anywhere within the program by declaring it with a public level of accessibility and using its fully qualified name.
For example, AddressInformation can be a nested type declared within Employee type, and can be accessed using its fully qualified name, Employee.AddressInformation.
Nested type has the following key properties:
- It can have different forms of accessibility that include private, public, protected, protected internal and internal. By default, it has private accessibility.
- It can access private and protected members of the containing type, including any inherited private and protected members. To access these members, an instance of the containing type has to be passed to the nested type through its constructor.
- It permits multiple nesting levels, which allows the code block of one nested class to be defined within another.
- It can inherit from the containing type and can also be inherited.
- Private members of the nested type are invisible to the containing type.
Nested type should not be used when it has to be publicly exposed for instantiation by the client code or if it is referenced directly in the client code. It cannot be used in place of namespace for logical grouping constructs.