Named argument in C# 4.0

4. May 2010

Named argument is a new feature in C# 4.0. Using this feature you do not need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. In this case documentation become really important. 
For example, a simple function that return the sum of two parameters can be called in the standard way by sending arguments for param1 and param2 by position, in the order defined by the function.

SimpleFunction(100, 50); 

If you do not remember the order of the parameters but you do know their names, you can send the arguments in either order, weight first or height first.

SimpleFunction(param1: 100, param1: 50);
SimpleFunction(param2: 50, param1: 100);

Named arguments also improve the readability of your code by identifying what each argument represents. But it doesn't mean your documentation become unnecessary. 
Also A named argument can follow positional arguments (which are not specified by parameter name), like:

SimpleFunction(100, param2: 50);

In this case you cannot change the order of the arguments. However, a positional argument cannot follow a named argument. Even you follow the current argument order.  The following statement causes a compile time error (Named argument specifications must appear after all fixed arguments have been specified).

SimpleFunction(param1 : 100, 50);

Full Code Example

namespace ConsoleApplication1
{
  class Program
  {

    static void Main(string[] args)

    {
      Console.WriteLine(SimpleFunction(100, 50));//Successful
      Console.WriteLine(SimpleFunction(param1: 100, param2: 50));//Successful
      Console.WriteLine(SimpleFunction(param2: 50, param1: 100));//Successful
      Console.WriteLine(SimpleFunction(100, param2: 50));//Successful
      Console.WriteLine(SimpleFunction(param1: 100, 50));//Error
    }

    static int SimpleFunction(int param1, int param2)
    {
      return param1 + param2;
    }
  }
}


Programming