Named Arguments avoids bugs on optional parameters

suggest change

Always use Named Arguments to optional parameters, to avoid potential bugs when the method is modified.

class Employee
{
    public string Name { get; private set; }

    public string Title { get; set; }

    public Employee(string name = "<No Name>", string title = "<No Title>")
    {
        this.Name = name;
        this.Title = title;
    }
}

var jack = new Employee("Jack", "Associate");   //bad practice in this line

The above code compiles and works fine, until the constructor is changed some day like:

// Evil Code: add optional parameters between existing optional parameters
public Employee(string name = "<No Name>", string department = "intern", string title = "<No Title>")
{
    this.Name = name;
    this.Department = department;
    this.Title = title;
}

//the below code still compiles, but now "Associate" is an argument of "department"
var jack = new Employee("Jack", "Associate");

Best practice to avoid bugs when “someone else in the team” made mistakes:

var jack = new Employee(name: "Jack", title: "Associate");

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents