Tuesday, April 15, 2008

Overloading Constructors

You have a class that you can initialize with different data. The consumer of your class might not have all the data though. You could solve this problem with multiple constructors.
public class Person
{
    private string _firstName;
    private string _lastName;

    public Person (string firstName)
    {
        _firstName = firstName;
    }

    public Person (string firstName, string lastName)
    {
        _firstName = firstName;
        _lastName = lastName;
    }
}
But you will notice you have some repeated code here, where _firstName is getting set to the parameter passed into both constructors. We can minimize duplicate code a couple ways.

One way is to have one constructor call another constructor:
public class Person2
{
    private string _firstName;
    private string _lastName;

    public Person2(string firstName)
        : this(firstName, string.Empty) {}

    public Person2(string firstName, string lastName)
    {
        _firstName = firstName;
        _lastName = lastName;
    }
}
Some people prefer to have all constructors call a single method:
public class Person3
{
    private string _firstName;
    private string _lastName;

    public Person3(string firstName)
    {
        Constructor(firstName, string.Empty);
    }

    public Person3(string firstName, string lastName)
    {
        Constructor(firstName, lastName);
    }

    private void Constructor(string firstName, string lastName)
    {
        _firstName = firstName;
        _lastName = lastName;
    }
}