Skip to content

Optional Parameters

In C#, optional parameters are parameters in a method that have default values specified in the method’s declaration. This means that when you call the method, you can omit values for these optional parameters, and the method will use the default values defined in its signature. Optional parameters can be used with methods and constructors.

Here is an example of how to use optional parameters in C#:

C#
public void ExampleMethod(int required, string optionalstr = "default string", int optionalint = 10)
{
    Console.WriteLine("{0}: {1}, {2}", required, optionalstr, optionalint);
}

In the above example, optionalstr and optionalint are optional parameters with default values of "default string" and 10, respectively. You can call this method in the following ways:

Info

Optional parameters must be listed at the end of the parameter list.

C#
ExampleMethod(1);
ExampleMethod(1, "new string");
ExampleMethod(1, "new string", 5);

In the first call, optionalstr and optionalint are set to their default values. In the second call, optionalstr is set to "new string", and optionalint is set to its default value. In the third call, both optionalstr and optionalint are set to the argument values.

Named Arguments

Named arguments enable you to specify an argument for a parameter by matching the argument with its name rather than with its position in the parameter list. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list. Named and optional parameters enable you to supply arguments for selected parameters.

Consider the following method:

C#
static void PrintOrderDetails(string sellerName, int orderNumber, string productName)
{
    Console.WriteLine($"Seller: {sellerName}, Order #: {orderNumber}, Product: {productName}");
}

You previously learned that when invoking this method, your arguments must follow the order of the parameters in the parameter list.

C#
PrintOrderDetails("Kenny", 12345, "Wrestling Boots");

With named arguments, you can order the arguments the way you want.

C#
PrintOrderDetails(productName: "Wrestling Boots", sellerName: "Kenny", orderNumber: 12345);

In the above example, the call the method using named arguments, which allows us to specify the values of the parameters by name instead of by position. This makes the code more readable and easier to understand.