Named real parameters and Optional real parameters Named and Optional Arguments, optionalarguments
1. Using "named real parameters", you can specify real parameters for a specific parameter by associating the name of the parameter that actually participates in the parameter, rather than the location of the parameter in the parameter list.
Static void Main (string [] args)
{
Console. WriteLine (CalculateBMI (weight: 123, height: 64); // name a real Parameter
Console. WriteLine ();
}
Static int CalculateBMI (int weight, int height)
{
Return (weight * 703)/(height * height );
}
With named arguments, you do not need to remember or find the order of the parameters in the list of parameters of the called method. You can specify the parameters for each real parameter by parameter name.
The following methods are all feasible:
CalculateBMI (height: 64, weight: 123 );
The named real parameters can be placed behind the positional real parameters, as shown in this case.
CalculateBMI (123, height: 64 );
However, the positional arguments cannot be placed behind the named arguments. The following statements may cause a compiler error.
// CalculateBMI (weight: 123, 64 );
2. The method, constructor, indexer, or delegate definition can specify whether the parameter is required or optional. Any call must provide real parameters for all required parameters, but the optional parameters can be omitted.
Static void Main (string [] args)
{
ExampleClass anExample = new ExampleClass ();
AnExample. ExampleMethod (1, "One", 1 );
AnExample. ExampleMethod (2, "Two ");
AnExample. ExampleMethod (3 );
ExampleClass anotherExample = new ExampleClass ("Provided name ");
AnotherExample. ExampleMethod (1, "One", 1 );
AnotherExample. ExampleMethod (2, "Two ");
AnotherExample. ExampleMethod (3 );
AnotherExample. ExampleMethod (4, optionalInt: 4); // use the real parameter name to skip the previous optional real parameters.
// AnotherExample. ExampleMethod (4, 4). An error is returned. You cannot skip several optional real parameters by default. You must assign values to the preceding real parameters in sequence.
}
Class ExampleClass
{
Private string _ name;
Public ExampleClass (string name = "default name") // The constructor parameter is an optional Real parameter.
{
_ Name = name;
}
Public void ExampleMethod (int reqired, string optionalstr = "default string", int optionalInt = 10) // the first one is required, and the last two are optional.
{
Console. WriteLine ("{0 }:{ 1}, {2} and {3}", _ name, reqired, optionalstr, optionalInt );
}
}