Implicit construction of objects
Thursday, January 3rd, 2008An hidden and not commonly used feature of C# is the implicit constructor. It is so uncommon to see it, that one time (in band camp), when I saw it being used, it took me a while to understand what is going on…
Actually, implicit construction is not a real feature by itself, but rather a by-product of implicit conversion between datatypes. Look here for more information about implicit conversions.
Anyway, what it means, is that the object is being constructed by an invisible factory method.
Take a look at this options to instantiate an object:
Telephone tel = new Telephone("972542221234"); // By Ctor
Telephone tel = Telephone.New("972542221234"); // Factory method
Telephone tel = "972542221234"; // Implicit Ctor
Here is the implementation of the telephone object I used for this example. The implicit constructor implementation is bolded:
public class Telephone { private readonly int countryCode; private readonly int areaCode; private readonly long phoneNumber; public Telephone(string phoneNumber) { // Dummy logic just for this example this.countryCode = Convert.ToInt32(phoneNumber.Substring(0, 3)); this.areaCode = Convert.ToInt32(phoneNumber.Substring(3, 2)); this.phoneNumber = Convert.ToInt64(phoneNumber.Substring(5)); } public int CountryCode { get { return countryCode; } } public int AreaCode { get { return areaCode; } } public long PhoneNumber { get { return phoneNumber; } } public static Telephone New(string phoneNumber) { return new Telephone(phoneNumber); } public static implicit operator Telephone(string phoneNumber) { return Telephone.New(phoneNumber); } }
This kind of syntax can help having less verbose code, and in software, less is usually more.