Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
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.
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:
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.