Named parameters are a handy tool to deal with parameters especially for readability as each parameter value can be marked with the parameter tag. The concept of Named parameters has been in .NET from the first version; however they were used only with Attributes as part of the ECMA-334 specifications. In .NET 4.0 the concept has been adopted also to functions.
In NET 4.0 named parameters are special instructions to the compiler to determine how the parameters need to be sorted out to match the method signature. This can be seen through the code generated by the compiler for the following C♯ lines.
Test("Hello", "World", "!");
Test("Hello", parameter2: "World", parameter3: "!");
Test(parameter3: "!", parameter1: "Hello", parameter2: "World");
ldstr "Hello"
ldstr "World"
ldstr "!"
call void NamedParameters.Program::Test(string, string, string)
ldstr "Hello"
ldstr "World"
ldstr "!"
call void NamedParameters.Program::Test(string, string, string)
ldstr "Hello"
ldstr "World"
ldstr "!"
call void NamedParameters.Program::Test(string, string, string)
The MSIL code above shows that after compilation both the traditional way of calling functions, i.e. with fixed parameters, and function calls with named parameters will generate the same type of code. A requirement is that named parameters must follow fixed ones. The reason for this restriction is that the compiler needs fixed parameters to be in their correct position as otherwise it won?t be able to determine their proper parameter relation.
References:
- MSDN: Named and Optional Arguments (C# Programming Guide)
- Standard ECMA-334: C# Language Specification