How to Overload Constructors in C#

by Al Beecy May 4, 2010
When providing overloads for a method signature, developers often implement the business logic just once in the version having the full list of parameters to avoid writing redundant code. The methods with the simpler signatures fill in default values and hand the call off to another of the signatures.

This same approach can also be used with constructors, but the syntax is slightly different than a normal method call:

public class MyClass


    private string _p1;

    private int _p2;

    private DateTime _p3;


    //This constructor calls another construtor

    //on this class to set default values.

    public MyClass() : this("example", 1)




    //This constructor also calls another construtor.

    public MyClass(string p1, int p2) : this(p1, p2, DateTime.Now)




    //This constructor does the actual work.

    public MyClass(string p1, int p2, DateTime p3)


        _p1 = p1;

        _p2 = p2;

        _p3 = p3;





Powered by BlogEngine.NET1.5.0.7 | Theme by Mads Kristensen