Site icon

Optional parameters in C#

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.

public static void OptionalParamDemo1(string firstName, string lastName, string salutation = "Mr.")
{            
     Console.WriteLine("{0} {1} {2}", salutation, firstName, lastName);
}

In above example code,

Lets have a look at another example.

using System;
namespace OptionalParameterDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Optional parameter demo method 1. ");
            //Optional parameter "salutaion" is not provided in method call.
            OptionalParamDemo1("John", "Davis");

            Console.WriteLine("Optional parameter demo method 2. ");
            //Optionl parameter "lastName" and "salutauion" is not provided in method call
            OptionalParamDemo2("John");

            Console.Read();
        }

        public static void OptionalParamDemo1(string firstName, string lastName, string salutation = "Mr.")
        {            
            Console.WriteLine("{0} {1} {2}", salutation, firstName, lastName);
        }

        public static void OptionalParamDemo2(string firstName, string lastName = "", string salutation = "Mr.")
        {
            Console.WriteLine("{0} {1} {2}", salutation, firstName, lastName);
        }
    }
}

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

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

Optional Parameter 1.0

Important points to remember.

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# (?.)

Exit mobile version