Parameters with default value. Hence, explicit values not specified in the calling place, default value has been taken.
1 2 3 4 |
|
p is the optional parameter here. By default Power does calculate square of v, if p value provided explicitly, does calculate v to the power of p.
1 2 |
|
Actually, two parameter target attributes help to make this feature available. These are:
- OptionalAttribute
- DefaultParameterValueAttribute
in System.Runtime.InteropServices namespace.
The OptionalAttribute marks the parameter as optional as like
1 2 3 |
|
The DefaultParameterValueAttribute constructor takes value parameter of type object is used to initialize the default value of the target parameter.
1
|
|
Points to be noted on “optional” parameter usage:
- Optional parameter should be the last parameter as like “param” usage ref and out parameters.
Named Parameters
Optional parameter will not be useful in real without named parameters. Yes, the name itself tells the answer. What will you do if you have more than one optional parameters and at the calling place, you want to pass actual value for less number of optional parameters. For example
1 2 3 4 |
|
Now, you want to pass the value of variable b only. Named parameter will help you.
Instead of parameter order, you can explictly specify parameter name along with the value using “:” in the calling place
See the following calling place
1
|
|
There is no surprising in the IL code, the compiler replaces optional parameters with default values as like below
1
|
|
The only thing to be considered is named and normal parameters can be mixed but normal parameter should be come first.