Named Arguments
Traditionally, the position of the arguments passed to a method call identified which argument that value was invoked with. It is possible in C# 4.0 to specify arguments by name, rather than position. This is helpful when many arguments are optional (by using the optional arguments feature) and you need to target a specific argument without having to specify all proceeding arguments up-to the argument concerned.
Named arguments can be used in combination with position arguments, although you must adhere to the following rules when calling a method using named arguments:
To understand the basic syntax, the following example creates a System.Drawing.Point by using named arguments. It should be noted that there is no constructor for this type that takes the y-size, x-size by position-this reversal is solely because of named arguments.
// reversing the order of arguments.Point p1 = new Point(y: 100, x: 10);
The following method invocations will not compile:
//"Named argument 'x' specifies a parameter for which a// positional argument has already been given"Point p3 = new Point(10, x: 10);// "Named argument specifications must appear after all// fixed arguments have been specified"Point p4 = new Point(y: 100, 10);// "The best overload for '.ctor' does not have a// parameter named 'x'"Point p5 = new Point(x: 10);
To demonstrate how to mix and match optional arguments and named arguments within method or constructor invocation calls, the code shown in Listing 8-2 calls the method definition for NewWay in Listing 8-1.
Listing 8-2: Mixing and matching positional and named arguments in a method invocation for methods that have optional and mandatory arguments
NewWay newWay = new NewWay();// skipping an optional parameternewWay.DoSomething( "({0},{1}) New way - param1 skipped.", param2: false);// any order, but if it doesn't have a default// it must be specified by name somewhere!newWay.DoSomething(param2: false,formatString: "({0},{1}) New way - params specified" + " by name, in any order.",param1: 5);