Optional Parameters , Named Arguments in C# 4

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:

image

When calling the above method we can explicitly pass two parameters to it:

image

Or we can omit passing the second optional parameter – in which case the default value of 0 will be passed:

image

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:

image

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):

image

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:

image

We could use named arguments to call the above method in any of the below ways:

image

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.

Declaration:

C#

image

VB

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s