C# 4.0 now supports using optional parameters with methods, constructors, and indexers (note: VB has supported optional parameters for awhile).
Parameters are optional when a default value is specified as part of a declaration. For example, the method below takes two parameters – a “category” string parameter, and a “pageIndex” integer parameter. The “pageIndex” parameter has a default value of 0, and as such is an optional parameter:
When calling the above method we can explicitly pass two parameters to it:
Or we can omit passing the second optional parameter – in which case the default value of 0 will be passed:
Note that VS 2010’s Intellisense indicates when a parameter is optional, as well as what its default value is when statement completion is displayed:
Named Arguments and Optional Parameters in C# 4.0
C# 4.0 also now supports the concept of “named arguments”. This allows you to explicitly name an argument you are passing to a method – instead of just identifying it by argument position.
For example, I could write the code below to explicitly identify the second argument passed to the GetProductsByCategory method by name (making its usage a little more explicit):
Named arguments come in very useful when a method supports multiple optional parameters, and you want to specify which arguments you are passing. For example, below we have a method DoSomething that takes two optional parameters:
We could use named arguments to call the above method in any of the below ways:
Because both parameters are optional, in cases where only one (or zero) parameters is specified then the default value for any non-specified arguments is passed.