Optional parameters and named arguments C# with Example



Optional parameters and named arguments C# with Example

We can omit the argument in the call if that argument is an Optional Argument Every Optional Argument has its 
own default value It will take default value if we do not supply the value A default value of a Optional Argument 
must be a 
1. Constant expression. 
2. Must be a value type such as enum or struct. 
3. Must be an expression of the form default(valueType) 
It must be set at the end of parameter list 
Method parameters with default values: 
public void ExampleMethod(int required, string optValue = "test", int optNum = 42) 
{ 
//... 
} 
As said by MSDN, A named argument , 
Enables you to pass the argument to the function by associating the parameter ’s name No needs for remembering 
the parameters position that we are not aware of always. No need to look the order of the parameters in the 
parameters list of called function. We can specify parameter for each arguments by its name. 
Named arguments: 
// required = 3, optValue = "test", optNum = 4 
ExampleMethod(3, optNum: 4); 
// required = 2, optValue = "foo", optNum = 42 
ExampleMethod(2, optValue: "foo"); 
// required = 6, optValue = "bar", optNum = 1 
ExampleMethod(optNum: 1, optValue: "bar", required: 6); 
Limitation of using a Named Argument 
Named argument specification must appear after all fixed arguments have been specified. 
If you use a named argument before a fixed argument you will get a compile time error as follows. 
Named argument specification must appear after all fixed arguments have been specified 
 

0 Comment's

Comment Form

Submit Comment