Software Architecture – C# 4.0- New Feature – Named Parameters and Optional Parameters

C# 4.0 introduced two new concepts as Named Parameters and Optional Parameters

Named Parameters:

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter’s name rather than with the parameter’s position in the parameter list.

Example:

public int CalculateSize(int Lenght , int Width ,  int Height)       
{        return Lenght + Width + Height;
 }

Can be called as

CalculateSize(1, 2, 2);            // call without named parameters
CalculateSize(Lenght:3, Height: 3, Width: 3);
CalculateSize(2, Height: 3, Width: 3); // A unnamed parameter can follow named parameter in argument list
CalculateSize(Lenght:3, Height: 3, 3); // Error: A named parameter can't follow unnamed parameters  in argument list

IntelliSense is shown for named parameters as shown below by specifying parameters name followed by “:”

Optional Parameters:
The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. Default values must be constants.
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters

public int CalculateSize(int Lenght , int Width ,  int Height = 6)
        {
         return Lenght + Width + Height;
       }

Here “Height” is Optional parameter because it default value is specified.

CalculateSize(3, 5); // Height is optional parameter,so can be skipped.
CalculateSize(3, , 5); //  Error: Width is not optional parameter,so can't be skipped
CalculateSize(3);   //Error: Invalid parameters

Optional parameters are shown by square brackets

Advertisements

2 Responses to Software Architecture – C# 4.0- New Feature – Named Parameters and Optional Parameters

  1. Mudasser says:

    you are sharing really Good Knowledge
    Best of Luck

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

%d bloggers like this: