I would say a use of nested types is for organization and specificity. The issue with a nested class like in your example is that an Engine
is a necessary object to all types of vehicles, therefore it doesn't quite make sense to have it nested within a particular vehicle.
You could say that perhaps using namespaces would still be better; after all, if you put the Engine
class within namespace CarsAreCool.Car
, you could still refer to the object by Car.Engine
, but that is really no different than an exposed property of type Engine
on the Car
class.
So here's where I view it as useful:
Say we have an interface IVehicle
which all our vehicles implement, and the other general classes relevant to a vehicle.
public interface IVehicle
{
public Engine Engine;
public int PassengerCapacity;
public int NumberOfWheels;
}
Car
, Truck
, Van
, Motorcycle
, etc would all implement this because it's a type of vehicle. Now take the Motorcycle
class for instance. Helmet is something that is pretty specific to motorcycles, and they have a few properties themselves, so it would be a bit tedious to have a property HelmetColor
, HelmetSize
, HelmetVisorType
off Motorcycle
wouldn't it? It would clearly make sense for these to be properties of the Helmet
class. Thus, you nest the class, such that it is only accessible when speaking about motorcycles, and it allows you to organize the properties in a clearer manner.
public class Motorcycle : IVehicle
{
#region IVehicle implementation
#endregion
#region Nested Types
public sealed class Helmet
{
public string Color;
public string Size;
public string VisorType;
public bool RequiredByLaw;
}
public Helmet Helmet;
public decimal Mileage;
#endregion
}