An optional parameter is a parameter that you can either include or omit when invoking the method. To specify that a parameter is optional, you need to include a default value for that parameter in the method declaration. The syntax for specifying the default value is the same as that of initializing a local variable. All required parameters must be declared before any optional parameters are declared. If there is a params parameter, it must be declared after all the optional parameters.
using System;
namespace OptionalParamter
{
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
int r0 = mc.Calc(); // Use explicit values.
int r1 = mc.Calc(5); // Use default for b.
Console.WriteLine($"{ r0 }, { r1 }");
}
}
public class MyClass
{
public int Calc(int a = 7)
{
return a + a;
}
}
}
You can mix them.
public int Calc(int x, int a = 7)