What is Constructor Chaining in C#? - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Thursday, January 5, 2012

What is Constructor Chaining in C#?

Constructor chaining is an approach where a constructor calls another constructor in the same or base class. You can't call constructors inside other constructors. A constructor can only chain another constructor to be called directly before it

First I would like to explain why need to Constructor chaining. Let take an example with Employee class.


class Employee {
    string _employeeType = "";
    string _id = "";
    string _fName = "";
    string _lName = "";

    public Employee (string id)
            {

            _employeeType = "<employee_type>";
        _id = id;

    }

    public Employee (string id, string fName)
       {
            _employeeType = "<employee_type>";
        _fName = fName;
        _id = id;

    }

    public Employee (string id, string fName, string lName) {
       
        _employeeType = "<employee_type>";
        _id = id;
        _fName = fName;
        _lName = lName;
    }
}





This code is not used the constructor chaining but here is the issue with duplicate code. 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 Employee {
    string _employeeType = "";
    string _id = "";
    string _fName = "";
    string _lName = "";

    public Employee (string id)
        this(id, """") {

    }

    public Employee (string id, string fName)
        this(id, fName, "") {

    }

    public Employee (string id, string fName, string lName) {
       
        _employeeType = "<employee_type>";

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



No comments:

Post a Comment