When you want to share initialization code among multiple constructors, there are generally two approaches. 

Initialization Method

The first approach is to create a private initialization method that you call from each constructor:

public class Test
{
    public Test( bool a, int b, string c )
    {
        this.m_C = c;
        this.Initialize( a, b );
    }
    public Test( bool a, int b, float d )
    {
        this.m_D = d;
        this.Initialize( a, b );
    }
    private void Initialize( bool a, int b )
    {
        this.m_A = a;
        this.m_B = b;
    }
    private bool m_A;
    public bool A { get { return this.m_A; } }
    private int m_B;
    public int B { get { return this.m_B; } }
    private string m_C;
    public string C { get { return this.m_C; } }
    private float m_D;
    public float D { get { return this.m_D; } }
}

Constructor Chaining

Another approach is to use constructor chaining, where a constructor calls another constructor in its class using the ": this()" designation as shown below:

public Test( bool a, int b, string c )
    : this( a, b )
{
    this.m_C = c;
}
public Test( bool a, int b, float d )
    : this( a, b )
{
    this.m_D = d;
}
private Test( bool a, int b )
{
    this.m_A = a;
    this.m_B = b;
}

Chaining is Better

As described in Nazish Ahsan’s blog, constructor chaining is preferred over an initialization method because it eliminates duplicate code and supports readonly members.

The compiler automatically adds code to constructors to initialize variables and call the base class constructor.  When you write your own common initialization function, the compiler duplicates this code in each constructor that calls the base constructor.  Using constructor chaining so that you have only one constructor calling the base constructor will eliminate this duplicate code.

In addition, you can initialize readonly members only in a constructor and not in a method.  So if the member m_A in our Test class is readonly, the first example would fail to compile since it tries to initialize the m_A readonly member in the Initialize method.  This means you must either duplicate read-only initialization code in every constructor (bad idea) or use constructor chaining as shown in the second approach (good idea).

Also notice in the second example how the chained constructor "Test( bool a, int b)" is marked private, even though the constructors that call it are public.  This allows you to hide chained constructors if desired.

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot