Optional Parameters
Optional parameters, as the name suggests, are optional and you have a choice whether to provide the argument or not. Optional parameters are assigned with default values. If you do not provide or give an argument corresponding to that optional parameter, then the default value will be used instead. Let’s look at the program in Example 1 for an example.
using System;
namespace OptionalParametersDemo
{
public class Program
{
static void PrintMessage(string message = "Welcome to Visual C# Tutorials!")
{
Console.WriteLine(message);
}
public static void Main()
{
PrintMessage();
PrintMessage("Learn C# Today!");
}
}
}
Example 1 – Optional Parameters Demo
Welcome to Visual C# Tutorials! Learn C# Today!
The PrintMessage() method has one optional parameter. To declare an optional parameter, simply provide it with a default value by using the assignment operator(=). We called the method twice. In the first call (line 14), we didn’t provide an argument so the method used the default message. On the second call(line 16), we passed a message and this message overrides the default message of the optional parameter.
If you have multiple arguments, all the optional arguments must come last. The three method headers below shows which are wrong and which is right.
void SomeMethod(int opt1 = 10, int opt2 = 20, int req1, int req2) //ERROR
void SomeMethod(int req1, int opt1 = 10, int req2, int opt2 = 20) //ERROR
void SomeMethod(int req1, int req2, int opt1 = 10, int opt2 = 20) //Correct
When calling methods with multiple optional parameters, you must still provide values for the optional parameters which are not in the last position. You cannot leave a gap like this:
void SomeMethod(int required1, int optional1 = 10, int optional2 = 20)
{
//Some Code
}
// ... Code omitted for demonstration
SomeMethod(10, , 100); //Error
If you want to skip an optional argument that is not in the last position, then you must take advantage of using named parameters.
SomeMethod(10, optional2: 100);
To use named arguments, you simply specify the name of the parameter followed by a colon, and the value that will be assigned to the parameter. The above method didn’t supply an argument for parameter optional1 therefore, it will use its default value indicated in the method declaration.