Named and Optional Parameters
Optional parameters, default values and named parameters are more interesting new features. Optional parameters let you avoid having to pass arguments when invoking methods. Default values let you provide any un-passed parameters with default values when invoking the method. Named parameters let you provide arguments using parameter names rather than by their position in the parameter list—meaning you can pass out-of-order named parameters to methods, and they'll work just fine. Here are some examples.
Consider the following method:
static int Add(int x = 0, int y = 0)
return (x + y);
As you can see, the parameters x and y have been given default values—the Add() method has default initializers in its parameters list. You can now call Add() without passing any parameters, as shown below:
int result = Add();
The preceding line returns 0, because both arguments get initialized to their default values.
Of course, you can also pass values explicitly:
int result = Add(5, 6); // returns 11
Optional parameters should appear at the end of the list in the method arguments; in other words, optional parameters should come last, after all the required parameters in the parameter list have been specified. Therefore, the following method is not valid:
static int Add(int x = 0, int y)
return (x + y);
If you compile that code, you'll see the error message "Optional parameters must appear after all required parameters."
However, you can now also pass values using named arguments, which removes the need to remember the order of parameters. Here's an example:
int result = Add( y:6, x:5); //returns 11
Notice that the preceding method call specifies y first, and then x, even though that's in reverse order from the parameter definitions in the Add() method.
The most important of all the new features added to C# 4.0 is the new dynamic keyword, which you can use to create objects even when you don't know the object type at compile time. You can get more information on the new features of C# 4.0 as well as a few samples of C# 4.0 Beta 1 code samples here.