1 out of 1 rated this helpful - Rate this topic

Recommendations on Nested Classes in Components

Visual Studio .NET 2003

The use of nested classes in your components is a powerful and convenient way to supply subordinate objects that your component might use. Nested classes allow your component to create and use objects without making them accessible or creatable by external users. Overuse of nested classes, however, can make your components difficult to work with and maintain. Here are some design recommendations that will help you to use nested classes in your components.

  • If your class is logically contained by another class, but has no stand-alone significance, implement it as a nested class. An example of this might be a Bearing class nested in a Wheel class. The Wheel object might need Bearing objects, but a client application would never have a need to create Bearing objects independent of a Wheel object.
  • If members of your class need to access private member variables of the object containing it, you can implement it as a nested class. For example, a Wheel object might have a private Radius field. If a Spoke object needs to access the Radius field, it can always have that access if it is implemented as a nested class.
  • If a class needs to implement an interface for interaction with other components, you can create an implementation of that interface as a nested class and expose an instance of the class as an interface property.
  • If your component will need to use one of several different subtypes of a contained object, but the subtype will not be known until run time, you can implement each subtype as a nested class as opposed to implementing all possible subtypes within a single class. When used with Just-In-Time compilation, nesting classes improves program performance because only the required type is compiled.
  • If other classes will reasonably need access, or will want to collect or contain your class, do not implement it as a nested class. A class that is accessed by several other classes should stand alone.
  • In general, do not implement public nested classes. Nested classes should primarily be for the internal use of the containing class. If you do implement a public nested class, it should be a class that logically belongs to the containing type, and is used infrequently. An exception would be if an instance of the nested class was exposed as a property on the containing class. For instance, a Wheel object might have a SpokesCollection nested class, an instance of which might be exposed as the SpokesCollection property.

See Also

Complex Components | Nested Classes in Components | Implementing Nested Classes

Did you find this helpful?
(1500 characters remaining)