Opsional and named parameters are features introduced in C# 4.0.
Defining and Invoking Standard Methods
void ProcessData(string identifier, int count)
{
// Implementation logic
}
static void Main()
{
// Standard call
ProcessData("example", 25);
}
When invoking a method, argument order must match the parameter declaration, and no parameters can be omitted.
Declaring and Using Optional Parameters
Optional parameters enable two scenarios: making some parameters optional, or making all parameters optional.
Making Some Parameters Optional
// 'identifier' is required, 'quantity' is optional with a default
void ExecuteTask(string identifier, int quantity = 10)
{
// Implementation logic
}
static void Main()
{
// Uses default for optional parameter
ExecuteTask("example"); // quantity = 10
// Provides value for optional parameter
ExecuteTask("example", 20); // quantity = 20
}
Mandatory parameters must be declared before opsional parameters in the parameter list. Violating this rule results in a compilation error.
Making All Parameters Optional
// Both parameters have default values
void Initialize(string name = "default", int value = 5)
{
// Implementation logic
}
static void Main()
{
// Various invocation patterns
Initialize(); // name="default", value=5
Initialize("custom"); // name="custom", value=5
Initialize("custom", 15); // name="custom", value=15
}
When all parameters are optional, their declaration order is flexible. However, invocation order must correspond to the declaration order unless named arguments are used.
Directly calling Initialize(15); would cause a compile-time error because the method expects a string for its first argument. To specify a value only for the second parameter, named arguments are required.
Employing Named Arguments
Named arguments are utilized at the call site to explicitly specify which parameter receives a value.
static void Main()
{
// Standard calls
Initialize();
Initialize("custom");
Initialize("custom", 15);
// Named argument call: specify only the 'value' parameter
Initialize(value: 15);
}
Named arguments resolve the issue of wanting to use the default for an earlier parameter while specifying a later one. They also allow arguments to be passed in any order:
Initialize(value: 15, name: "custom"); // Valid call with out-of-order arguments
The Visual Studio IntelliSense indicates optional parameters and their defaults using square brackets, for example: Initialize([string name = "default"], [int value = 5]).