Optional Parameters in C# 4.0
C# 4.0 has introduced Optional Parameters as a new feature.
"Optional Parameters in C# 4.0" article includes definition,usage of it. It also includes small example alongwith description. I hope it will be useful to you.
Optional Parameters in C# 4.0
C# 4.0 has introduced new features such as Named Parameters and Optional Parameters. These are distinct features but come along with each others.
In this article we will explore about Optional Parameters.
Methods can have optional parameters which allow the calling method to vary the number of arguments to pass.
Each optional parameter has a default value as part of its definition.
If no argument is sent for that particular parameter, then the default value is used.
We can also omit parameters which have a defined default value.
It is possible to create methods with one or more optional parameters.
For e.g Public int Sqaure( int number, int raisedtovalue = 2)
Sqaure() //It will throw runtime error , as at least one parameter is required
Sqaure(2) // In this case argument 1 is equal to 2 and argument 2 is default value which is 2
All optional parameters must be placed at the end of the parameter list.
It can be used in methods , constructors, and indexers.
Named arguments free you 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. For example, a function that calculates body mass index (BMI) can be called in the standard way by sending arguments for weight and height by position, in the order defined by the function.
CalculateBMI(123, 64);
If you do not remember the order of the parameters but you do know their names, you can send the arguments in either order, weight first or height first.
CalculateBMI(weight: 123, height: 64);
CalculateBMI(height: 64, weight: 123);
Named arguments also improve the readability of your code by identifying what each argument represents.
A named argument can follow positional arguments, as shown here.
CalculateBMI(123, height: 64);
However, a positional argument cannot follow a named argument. The following statement causes a compiler error.
//CalculateBMI(weight: 123, 64);