Visual C# 4.0 Named Arguments

Here are how Named Arguments in C# 4.0 works. This is a very nice feature that enables better code readability and also is a must combined with Optional Arguments. We have now dug ourselves out of the crazy “method overload overload”… If you catch what I mean? I posted about Optional Arguments here: Visual C# 4.0 Optional Arguments – FINALLY

Here are my sample on Optional Arguments from the last post again:

public Person(int shoesize = 8, string name = "Eve", Gender gender = Gender.Female)
{   }

The great thing about it is that this constructor can be called in all these cool ways:

var person = new Person(12, gender: Gender.Male);
person = new Person(12, name: "Jones");
person = new Person(12, gender: Gender.Male, name: "Smith");
person = new Person(12, name: "Smith", gender: Gender.Male);

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list.

The really cool thing, which is potentially quite useful, is that when you use named arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. This would make some API calls more logical and more readable for another developer that reads the code.

For more information about preferred type conversions, see the following section in the C# Language Specification:

Cheers,

M.

Technorati Tags: ,,
Digg This

posted @ Tuesday, October 13, 2009 9:09 PM

Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
Please add 8 and 4 and type the answer here:
 

Live Comment Preview: