C# Optional Parameters


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.

1using System;
2namespace OptionalParamter
3{
4    class Program
5    {
6        static void Main(string[] args)
7        {
8            MyClass mc = new MyClass();
9            int r0 = mc.Calc(); // Use explicit values.
10            int r1 = mc.Calc(5); // Use default for b.
11            Console.WriteLine($"{ r0 }, { r1 }");
12        }
13    }
14    public class MyClass
15    {
16        public int Calc(int a = 7)
17        {
18            return a + a; 
19        }
20    }
21}

You can mix them.

1public int Calc(int x, int a = 7)