Now it’s around a month, that Microsoft released the .NET framework 4 to the public – so I wanted to take the occasion to give you a quick view on two nice new features:
1. Optional parameters:
You can specify any parameters to be optional by assigning it a default value directly in the list of parameters (using the assignment operator). It is quite straight-forward:
Snippet 1: The DoSomething method, specifying the count parameter as optional
This changes also the way such a method can be called, i.e. by omitting the parameter it still works fine – it just assigns the default value (in our case 10), and the code can perfectly run like that. Hence, a call to the method may look like in the following example:
Snippet 2: Call to DoSomething , omitting the parameter
Even IntelliSense takes notice of the optional parameters, displaying them in square brackets, along with its default value:
Figure 1: IntelliSense displaying an optional parameter
Straightforward so far, isn’t it?
2. Named parameters
Now, imagine a case where we have a method that defines two required parameters, followed by an optional parameter and then again followed by another requited parameter. Let’s change the DoSomething method so it looks like in snippet 3:
Snippet 3: The changed DoSomething method
Now it is basically possible to change the order of the parameter calling by specfying the correct names followed by a colon and again followed by the value. That’s it!
This feature is especially useful if you use optional parameters, since it may not become clear which parameter is called next if you omit an optional parameter. Again, IntelliSense gives useful hints when calling a named parameter.