C# 4.0 introduced two simple yet very handy concepts regarding method parameters. They are Optional parameters and Named parameters.

What is optional parameter in C# ?

As name suggests, Optional parameter are not compulsory but are optional in method invocation. There is no keyword to declare Optional parameters in C#, However we can specify default value in the method declaration to specify a parameter as optional,

Lets have a look at below example.

In above example code,

  • We have declared a method OptionalParamDemo1() that has a Optional parameter as salutation having a default value assigned as "Mr." .
  • During method invocation, if the value for the parameter salutation is not provided then the default value as "Mr." will be used in side the method.

Lets have a look at another example.

In above example, We have declared two methods each having optional parameters.

  • In method, OptionalParamDemo1(string firstName, string lastName, string salutation = "Mr.") parameter salutation is optional parameter. During the method call OptionalParamDemo1("John", "Davis"); the value of optional parameter is not provided, hence the default value “Mr.” is used.
  • Similarly, in second method OptionalParamDemo2(string firstName, string lastName = "", string salutation = "Mr.") , both the parameter lastName and salutation are optional. During method call OptionalParamDemo2("John"); Only one parameter value is passed and the value of optional parameters is not provided, hence the default value “” and “Mr.” are used.

When we run above sample code then the output is as follows.

Optional Parameters output 1.0
Optional Parameter 1.0

Important points to remember.

  • You can use Optional Parameter in methods, constructor method, indexers and delegates.
  • In a method, If you have parameters without default values then they must come before all Optional parameters with default values.
  • Default values assigned to an optional parameter must be a constant value that can be derived at compile time.
  • If there are parameter with ref and out keywords then you shouldn’t use them as Optional parameter, because you wont be able to pass correct default values to these type of parameters.

Thanks for your time 🙂 feel free to provide your feedback and do check my other blogs on Null Coalescing Operator (??) in C#  and  Conditional Operator in C# (?.)