#628 – Why You Might Create a Nested Type

The most common reasons for creating a nested type–one type defined within another one–are:

  • For information hiding purposes, so only the outer type has access to the type being defined
  • As a way of organizing your code, associating a sub-type with the parent type where it is used

One scenario might be that you define several subclasses inside of a parent class and make the subclasses private.  You might also use the parent class as a factory, returning instances of the subclass (but visible to client through the parent class’ type).  Doing this guarantees that no code outside of the parent class can directly work with the subclasses, but has to go through the parent class to instantiate them.