C# 4.0: Named Argument

Okay, we saw Optional Parameters, an upcoming feature of C# 4.0, in the last post and one reader of my blog asked me a question related to “Optional Parameters”. I don’t believe I have readers of my blog as well 🙂 but that was also one of my friend :p

So, in last post, we discussed an example of Employee class in which we passed some optional parameters in constructor:

public Employee(string firstName, string lastName, string qualification = "N/A", string middleName = "")

and I can simply call that like:

Employee emp= new Employee("Adil", "Mughal");

The great question was that Is there any way that we can skip qualification i.e. third parameter and give last parameter of middleName? He seems to be good reader or he might have listened to Anders Hejlsberg’s session 😉

The answer of this question is that Yes absolutely we can and that feature is called Named Argument in C# 4.0. We can simply do this like:

Employee emp = new Employee("Adil", "Mughal", middleName: "Ahmed");

Good enough to answer the query :). Now let’s do some changes with the Employee constructor and make lastName optional as well:

public Employee(string firstName, string lastName = "", string qualification = "N/A", string middleName = "")

Now I can instantiate object of Employee in quite simple and flexible ways

Employee("Adil", qualification:"BS");
Employee("ABC", lastName: "EFG", qualification: "BS");
Employee("XYZ", middleName: "MNO");

These upcoming features are really cool as they will improve productivity of cool enough to help C# developers avoid writing ‘n’ number of overloads though some of them are not new in the programming languages’ world.