Friday, 9 January 2015

Combining constructors in C# - Cascading constructors

We have a basic Address class.

public class Address
{
public Guid addressId { get; set; }
public string houseNumber {get;set;}
public string additionalAddressInfo { get; set; }
public string roadName {get;set;}
public string town { get; set; }
public float? latitude { get; set; }
public float? longitude { get; set; }


   public Address(string houseNumber, string additionalAddressInfo, string roadName, string town, float? latitude, float? longitude)
   {
   this.addressId = System.Guid.NewGuid();
   this.houseNumber = houseNumber;
   this.additionalAddressInfo = additionalAddressInfo;
   this.roadName = roadName;
   this.town = town;
   this.latitude = latitude;
   this.longitude = longitude;
   }


   public Address(AddressFromCSV addressFromCSV) : this(addressFromCSV.houseNumber, addressFromCSV.additionalAddressInfo,
   addressFromCSV.roadName,addressFromCSV.town,addressFromCSV.latitude,addressFromCSV.longitude)
   {
   }
}

and additional class that inherits from Address class.
public class AddressFromCSV : Address
{
   public string source { get; set; }
   public DateTime csvUploadedDate { get; set; }
   public string uploadedBy { get; set; }
   public string browserType { get; set; }
}
We are using AddressFromCSV  when uploading csv file with addresses.

We want to create a new Address object from AddressFromCSV class. There are few ways of doing that.
We can create new new Address and pass all fields from AddressFromCSV class.
Address address = new Address(addressFromCSV.houseNumber, addressFromCSV.additionalAddressInfo, addressFromCSV.roadName, addressFromCSV.town, addressFromCSV.latitude, addressFromCSV.longitude);
Or we can use cascading constructor and pass whole AddressFromCSV class to Address constructor.
We already defined constructor in Address that will expecAddressFromCSV class so all we have to do is to pass this class.

Address address = new Address(addressFromCSV);
As you can see second method is much cleaner and if we want to change something in the future we have to do it only in one place - in Address constructor.