Learn the new features of c#4.0: Optional parameters, named parameters, parameter arrays.
1, optional parameter, refers to the method's specific parameters to specify the default value, you can omit these parameters when calling the method.
But be aware that:
(1) The optional parameter cannot be the 1th parameter of the parameter list, and must be located after all required parameters (unless there is no required parameter);
(2) An optional parameter must specify a default value, and the default value must be a constant expression and cannot be a variable;
(3) All parameters after the optional parameter must be an optional parameter.
2, named parameters, refers to the call through named parameters, the actual parameter sequence can be different from the formal parameters.
3. Parameter array, define the parameter array through the keyword params. You can pass in a number of different arguments at the time of invocation, with good flexibility.
4, the specific code:
//Optional parameters
static int Add ( int a, int b = 2)
{
return a + B;
}
//parameter array, 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 by named arguments, the argument order can be different from the formal parameter
Console.WriteLine (Add (B:6, a:1));
Calling a method that uses a parameter array
Console.WriteLine (ADD (1, 3,5));
Console.WriteLine (ADD (1, 3, 5,7));
Console.readkey ();
}
C # Optional parameters, named arguments, parameter arrays