Optional parameters and named arguments
suggest changeWe can omit an optional argument. Every optional argument has its own default value, and it takes that default if we do not supply one. The default must be a constant expression, new ValType() for a value type, or default(ValType) for a value type. A reference type can use a constant such as null or a string literal. Optional parameters must come after all required parameters.
Method parameters with default values:
public void ExampleMethod(int required, string optValue = "test", int optNum = 42)
{
//...
}
As said by MSDN, a named argument lets you pass a value by the parameter’s name. You do not have to remember the position of a parameter you are skipping, or look up the full parameter order. Each argument can be specified by its parameter 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
Through C# 7.1, named arguments must appear after all positional arguments. A named argument before a positional one is a compile-time error, as in the following image. Starting in C# 7.2, a named argument may come first when it still occupies its own position.
Named argument specification must appear after all fixed arguments have been specified