Optional and Named Arguments in C#


Introduction

One of the new interesting features in Visual Studio 2010 is "Named and Optional" arguments. Practically, they are very useful together but both are quite different.

Optional Arguments

Optional Arguments enable us to omit arguments for some parameters. Any call must provide arguments for all required parameters but can omit arguments for optional parameters. The parameter which is omitted has default value as part of its definition. If no argument is sent for that the default value automatically will be used. Optional parameters are defined at the end of the parameter list after any required parameters.

image001.gif

In above example, we are not providing the value for the "width" parameter because it is optional. If you do provide the "width" parameter a value then it will override the default value. For example:

image003.jpg


In the above example, the width value will be replaced by 6.

Named Arguments

Named Arguments enable us 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. It frees us from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name.

image005.jpg

In the above example, if we replace the positional (non-named) arguments by named arguments then we will have no concern about the order of the arguments.

HAVE A HAPPY CODING!!


Recommended Free Ebook
Similar Articles