c optional named parameters

  • 2020-05-07 20:19:20
  • OfStack

When reasserting an argument that assigns a default value, you can explicitly assign a value to the name of the specified argument, but implicitly, by inference from the c# compiler, based on the order of the method arguments.

Code example:
 
void M(int x=9,string s="a",DateTime dt = default(DateTime)) 
{...} 

Main() 
{ 
M();// Use default values  
M(8,"b"):// Method parameters are implicitly specified, with no default values specified  
M(6,"v",DateTime.Now);// Same as above  
M(6,dt:DateTime.Now);// Explicitly the name of the specified parameter, passing the value for the specified parameter  
} 

Guidelines to use:
1. You can specify default values for methods and argument properties
2. Parameters with default values must be defined after parameters without default values
3. The default parameter must be constant
4. Default values cannot be specified for the ref and out parameters

Related articles: