C# 4.0 – Named Parameters

C# 4.0 introduces named parameters which is primarily for code readability or for use with optional parameters.Named parameters free developers from the requirement to remember or to look up the order of parameters in the method’s signature. The parameter for each argument can be specified by providing the parameter name.

For example, a function which calculates travel time could be called in the standard way by providing arguments for distance and speed in the order defined by the function:

calcTravelTime(52, 45);

However, if you don’t know the order of the parameters but you do know the parameter names, you can call the function by proving the parameters in any order, for example:

calcTravelTime(speed: 45, distance: 52);

or

calcTravelTime(distance: 52, speed: 45);

Named parameters improves code readability  by identifying what each parameter represents.

A named parameter can follow positional arguments, for example:

calcTravelTime(52, speed: 45);

But note that a positional parameter cannot follow a named parameter. This causes an error:

calcTravelTime(distance: 52,  45); //Causes an error

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!