The example you showed is not a nested class, but a property making use of another class through composition.
The main advantage in your example is that the
Address
is a separate entity (refactored out) and may be used to indicate different classifications of address for a givenCustomer
e.g a Customer may have aHome Address
, aBusiness Address
and aCorporate Address
which all will be of typeAddress
class.
Achieving above type of classification without having a separate Address
class would be difficult otherwise and that's the one reason Address
is taken out as a separate class.
As an illustration, your Customer
class can be modified as below to show one of the advantages:
public class Customer
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address HomeAddress { get; set; }
public Address BusinessAddress { get; set; }
public Address CorporateAddress { get; set; }
}
Now, as per above example if your Address
entity later requires ZipCode
also, then you don't need to add 3 zipcodes (1 for Home, 1 for Business and 1 for Corporate); you just add the ZipCode
property to the Address
class and the 3 properties in Customer
class make use of the new property without modifying the Customer
class.