What is an Optional parameter in C#?


By default, all parameters of a method are required. A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments.

The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used.

Thera are different ways to make a parameter optional.

Using Default Value

Example

 Live Demo

using System;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         OptionalMethodWithDefaultValue(5);
         //Value2 is not passed as it is optional
         OptionalMethodWithDefaultValue(5, 10);
         //Value2 is passed
         Console.ReadLine();
      }
      public static void OptionalMethodWithDefaultValue(int value1, int value2 = 5){
         Console.WriteLine($"Sum is {value1 + value2}");
      }
   }
}

Output

The output of the above code is

Sum is 10
Sum is 15

In the above example, the method OptionalMethodWithDefaultValue(int value1, int value2 = 5) value2 is having default value 5. So if no arguments is passed for value2 while calling it will take the default value 5 and if an argument is passed for value2 then the default value is overridden.

Using Optional Attribute

Example

 Live Demo

using System;
using System.Runtime.InteropServices;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         OptionalMethodWithDefaultValue(5);
         OptionalMethodWithDefaultValue(5, 10);
         Console.ReadLine();
      }
      public static void OptionalMethodWithDefaultValue(int value1, [Optional]int value2){
         Console.WriteLine($"Sum is {value1 + value2}");
      }
   }
}

Output

The output of the above code is

Sum is 5
Sum is 15

Here for the [Optional] attribute is used to specify the optional parameter.

Also, it should be noted that optional parameters should always be specified at the end of the parameters. For ex − OptionalMethodWithDefaultValue(int value1 = 5, int value2) will throw exception.

Example

using System;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         OptionalMethodWithDefaultValue(5);
         OptionalMethodWithDefaultValue(5, 10);
         Console.ReadLine();
      }
      public static void OptionalMethodWithDefaultValue(int value1 = 5, int value2){
         Console.WriteLine($"Sum is {value1 + value2}");
      }
   }
}

Error − Optional Parameters must appear after all required parameters.

Updated on: 04-Aug-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements