Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Constructor Chaining in C#

0.00/5 (No votes)
20 Oct 2011 1  
Constructor Chaining is an approach where a constructor calls another constructor in the same or base class.

What is Constructor Chaining?

Constructor Chaining is an approach where a constructor calls another constructor in the same or base class.

This is very handy when we have a class that defines multiple constructors. Assume we are developing a class Student. And this class has three constructors. On each constructer, we have to validate the student's ID and categorize him/her. So if we do not use the constructor chaining approach, it would be something similar to what is shown below:

271582/screen_01_thumb_2_.png

Even though the above approach solves our problem, it duplicates code. (We are assigning a value to ‘_id’ in all our constructors). This is where constructor chaining is very useful. It will eliminate this problem. This time, we only assign values in one constructor which consists of the most number of parameters. And we call that constructor when the other two constructers are called.

class Student {
    string _studentType = "";
    string _id = "";
    string _fName = "";
    string _lName = "";

    public Student(string id)
        : this(id, "", "") {

    }

    public Student(string id, string fName)
        : this(id, fName, "") {

    }

    public Student(string id, string fName, string lName) {
        //Validate logic.....
        _studentType = "<student_type>";

        _id = id;
        _fName = fName;
        _lName = lName;
    }
}

**Please note: If you do not specify anything [in this example, we used ‘this’), it will be considered that we are calling the constructor on the base class. And it’s similar to using ‘: base(…)’].

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here