FREE BOOK

Chapter 8: C# 4.0 Features

Posted by Addison Wesley Free Book | C# Language February 02, 2010
This chapter looks at the new features added into C# 4.0 that combine to improve code readability and extend your ability to leverage LINQ to Object queries over dynamic data sources.

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:

  1. If you are going to use a combination of positional and named arguments, the positional arguments must be passed first (they cannot come after named arguments).
  2. All non-optional arguments must be specified somewhere in the invocation, either by name or position.
  3. If an argument is specified by position, it cannot then be specified by name as well.

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 parameter

newWay.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);

Total Pages : 11 34567

comments