#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.

Advertisement

#251 – Class Properties Support the Principle of Encapsulation

Encapsulation is one of the core principles of object-oriented programming.  Encapsulation is the idea of hiding implementation details of a class from the users of that class and only exposing a public interface.

Class properties in C# support the idea of encapsulation.  Client code that wants to read or write a property has access only to its public interface–the data type of the property and the knowledge that there is a get or a set accessor (or both) for that property.

Client code that reads or writes a property has no information about:

  • How the class actually stores the property data
  • The implementation of the get accessor–how data is retrieved when a client reads the property value
  • The implementation of the set accessor–how data is stored when a client writes the property value