Named Parameters

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.

  1. Test("Hello", "World", "!");
  2. Test("Hello", parameter2: "World", parameter3: "!");
  3. Test(parameter3: "!", parameter1: "Hello", parameter2: "World");
  1. ldstr      "Hello"
  2. ldstr      "World"
  3. ldstr      "!"
  4. call       void NamedParameters.Program::Test(string, string, string)
  5.  
  6. ldstr      "Hello"
  7. ldstr      "World"
  8. ldstr      "!"
  9. call       void NamedParameters.Program::Test(string, string, string)
  10.  
  11. ldstr      "Hello"
  12. ldstr      "World"
  13. ldstr      "!"
  14. 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:

Be Sociable, Share!