Sunday, November 2, 2008

Nested Type Usage

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:
1. The nested type logically belongs to the containing type.
2. The nested type is not used often, or at least not directly.
The following examples illustrates how to define types with and without nested types:
Visual Basic
' 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:
1. The type is used in many different methods in different classes. The FileMode Enumeration is a good example of this kind of type.
2. The type is commonly used in different APIs. The StringCollection class is a good example of this kind of type.

No comments: