Reshef’s tip of the day

.net development tips

Implicit construction of objects

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

Tags: ,

3 Responses to “Implicit construction of objects”

  1. Noy Says:

    great post!

    what about performance wise?
    is it act differently?

  2. reshef Says:

    I didn’t test performance but there should be no problem since all it does is to call a static method.

  3. nadav Says:

    This is very nice, but it is only useful when the object we construction is based on one object.

    I like what you said about less being more and i agree. i think this does look nicer and a little clearer to “the non-programmer”.
    And usually when codding we try to make it understandable by him, if he gets it, everyone gets it.

    nice post =]

Leave a Reply

Jajah is the VoIP player that brought you web-activated telephony.