Поделиться через


Nested Type Usage Guidelines

A nested type is a type defined within the scope of another type. Nested types are very useful for encapsulating implementation details of a type, such as an enumerator over a collection, because they can have access to private state.

Public nested types should be used rarely. Use them only in situations where both of the following are true:

  • The nested type (inner type) logically belongs to the containing type (outer type).

The following examples illustrates how to define types with and without nested types:

' With nested types.
ListBox.SelectedObjectCollection 
' Without nested types.
ListBoxSelectedObjectCollection  

' With nested types.
RichTextBox.ScrollBars 
' Without nested types.
RichTextBoxScrollBars 
[C#]
// With nested types.
ListBox.SelectedObjectCollection 
// Without nested types.
ListBoxSelectedObjectCollection  

// With nested types.
RichTextBox.ScrollBars 
// Without nested types.
RichTextBoxScrollBars 

Do not use nested types if the following are true:

  • The type must be instantiated by client code. If a type has a public constructor, it probably should not be nested. The rationale behind this guideline is that if a nested type can be instantiated, it indicates that the type has a place in the library on its own. You can create it, use it, and destroy it without using the outer type. Therefore, it should not be nested. An inner type should not be widely reused outside of the outer type without a relationship to the outer type.
  • References to the type are commonly declared in client code.

See Also

Design Guidelines for Class Library Developers