Sunday, August 29, 2010

Named Parameter feature of C#.Net 4.0

Lets assume, your constructor definition looks like this:
public Employee(string firstName, string lastName, DateTime dateOfBirth)

In that case, you have no other option in C# 3.0 other than to invoke the constructor like this:
Employee employee = new Employee ("Shweta", "Jain", new DateTime(1990, 1, 1));


So, now in this case, it is not clear about what is being assigned in the constructor (e.g., that third DateTime parameter might be date of birth, might be date hired, who knows).  
In C# 4.0, you can invoke the constructor like this:

Employee employee = new Employee(firstName: "Shweta", lastName: "Jain", dateOfBirth: new DateTime(1990, 1, 1));
This expresses the intent clearly and makes the code more understandable.