I learned new features of C #4.0: optional parameters, named parameters, and parameter arrays.
1. Optional parameters: Specify the default value for a specific method parameter. You can omit these parameters when calling a method.
Note:
(1) The optional parameter cannot be the 1st parameter in the parameter list. It must be placed after all required parameters (unless there are no required parameters );
(2) A default value must be specified for an optional parameter. The default value must be a constant expression and cannot be a variable;
(3) All optional parameters later must be optional.
2. Named parameters are called by named parameters. The real Parameter order can be different from that of the form parameter.
3. Parameter array. The parameter array is defined by the keyword Params. Different real parameters can be input during the call, providing great flexibility.
4. Specific Code:
// Optional parameter
Static int add (int A, int B = 2)
{
Return A + B;
}
// Parameter array, with the keyword Params
Static int add (Params int [] P)
{
Int sum = 0;
Foreach (int I in P)
Sum + = I;
Return sum;
}
Static void main (string [] ARGs)
{
Console. writeline (add (1 ));
Console. writeline (add (1, 3 ));
// Called using named parameters. The real Parameter order can be different from that of the form parameter.
Console. writeline (add (B: 6, A: 1 ));
// Call the method that uses the parameter Array
Console. writeline (add (1, 3, 5 ));
Console. writeline (add (1, 3, 5, 7 ));
Console. readkey ();
}