How to make Optional Parameters in C#

How to make Optional Parameters in C# with Examples

In this article, I am going to discuss How to make Optional Parameters in C# with Examples. Please read our previous article, where we discussed Automappers in C#. This is also one of the most frequently asked interview questions. So here we will discuss the different options that are available in C# to make the method parameters optional.

How to make Optional Parameters in C#?

We can make the method parameters optional in C# in many different ways as follows.

  1. Using Parameter Array
  2. Method Overloading
  3. Specify Parameter Defaults
  4. Using OptionalAttribute 

So, let us discuss all these options one by one with examples.

Using Parameter Array to Make Optional Parameter in C#:

Let us understand how to make method parameters optional using parameter array in C# with an example. Consider the following ADDNumbers method. Here, we are declaring the first and second parameters as integers and the third parameter is a parameter array i.e. params object[].

Using Parameter Array to Make Optional Parameter in C#

The above ADDNumbers method allows the user to add 2 or more numbers. The FN and SN parameters are mandatory parameters whereas the restOfTheNumbers parameter is optional. If the user wants to add just two numbers, then he can invoke the method as shown below
ADDNumbers(10, 20);
On the other hand, if the user wants to add 5 numbers, then he can invoke the method in the below two ways.
ADDNumbers(10, 20, 30, 40, 50);
or
ADDNumbers(10, 20, new object[]{30, 40, 50});

The parameter array must be the last parameter in the formal parameter list. The following function will not be compiled as the parameter array not the last parameter of the parameter list.

How to make Optional Parameters in C# with Examples

The complete example is given below.
using System;
namespace OptionalParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            ADDNumbers(10, 20);
            ADDNumbers(10, 20, 30, 40);
            ADDNumbers(10, 20, new object[] { 30, 40, 50 });
            Console.ReadLine();
        }

        public static void ADDNumbers(int FN, int SN, params object[] restOfTheNumbers)
        {
            int result = FN + SN;
            foreach (int i in restOfTheNumbers)
            {
                result += i;
            }
            Console.WriteLine("Total = " + result.ToString());
        }
    }
}
Output:

How to make method parameters optional in C#

Using Method Overloading to Make Optional Parameter in C#:

Let us understand how to make method parameters optional using method overloading in C#. Let create the following method which will add any number of integers. Here, we created, the first two parameters as integers and the third parameter is an integer array. The first two parameters are mandatory and in the case of the third parameter, if you don’t want to pass any value, then you simply need to pass null.

Using Method Overloading to Make Optional Parameter in C#

If you want to add 5 integers, let’s say 10, 20, 30, 40, and 50 then you need to call the method as shown below.
ADDNumbers(10, 20, new int[]{30, 40, 50});
At the moment all the 3 method parameters are mandatory. Now, if I want to add just 2 numbers, then I can invoke the method as shown below.
ADDNumbers(10, 20, null);
Notice that, here I am passing null as the argument for the 3rd parameter. We can make the 3rd parameter optional by overloading ADDNumbers() function which takes two parameters as shown below.

How to make Optional Parameters in C#

Now, we have 2 overloaded versions of the ADDNumbers() function. If we want to add just 2 numbers, then we can use the overloaded version of ADDNumbers() function which takes 2 parameters as shown below.
ADDNumbers(10, 20);
Similarly, if we want to add 3 or more numbers, then we can use the overloaded version of ADDNumbers() function which takes 3 parameters as shown below.
ADDNumbers(10, 20, new int[] { 30, 40 }); 

The complete example is given below
using System;
namespace OptionalParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            ADDNumbers(10, 20);        
            ADDNumbers(10, 20, new int[] { 30, 40, 50 });
            
            Console.ReadLine();
        }

        public static void ADDNumbers(int FN, int SN, int[] restOfTheNumbers)
        {
            int result = FN + SN;
            foreach (int i in restOfTheNumbers)
            {
                result += i;
            }
            Console.WriteLine("Total = " + result.ToString());
        }

        public static void ADDNumbers(int FN, int SN)
        {
            int result = FN + SN;
            Console.WriteLine("Total = " + result.ToString());
        }
    }
}
Output:

How to make method parameters optional in C#

Making Method Parameters Optional by Specifying Parameter Defaults in C#

Let us understand how to specify the parameter defaults to make the make method parameters optional in C#. We can make the method parameter optional by specifying a default value of null as shown below. As you can see in the below image, we have made the third parameter optional by specifying a default value null. Here, the first and second parameters are mandatory parameters.

Making Method Parameters Optional by Specifying Parameter Defaults in C#

As we have specified a default value for the 3rd parameter now it becomes optional. So, if we want to add just 2 numbers, we can invoke the method as shown below.
ADDNumbers(10, 20);
On the other hand, if we want to add 3 or more numbers, then we can invoke the method ADDNumbers() as shown below.
ADDNumbers(10, 20, new int[] { 30, 40 }); 
The Optional parameters in C# must appear after all the required parameters. The following method will not be compiled. This is because, we are making the parameter “restOfTheNumbers” optional, but it appears before the required parameters “SN”.

How to make Optional Parameters in C# with Examples

Named Parameters in C#:

In the following method, the parameters “b” & “c” are optional.

Named Parameters in C#

When we invoke the above method as shown below “1” is passed as the argument for parameter “a” and “2” is passed as the argument for parameter “b” by default.
Test(1, 2);

My intention is to pass “2” as the argument for parameter “c”. To achieve this we can make use of named parameters, as shown below. Notice that, I have specified the name of the parameter for which value “2” is being passed.
Test(1, c: 2); 

The complete example is given below.
using System;
namespace OptionalParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            ADDNumbers(10, 20);        
            ADDNumbers(10, 20, new int[] { 30, 40, 50 });
            Test(1, 2);
            Test(1, c:2);
            Console.ReadLine();
        }

        public static void ADDNumbers(int FN, int SN,  int[] restOfTheNumbers = null)
        {
            int result = FN + SN;
            // loop thru restOfTheNumbers only if it is not null otherwise 
            // you will get a null reference exception
            if (restOfTheNumbers != null)
            {
                foreach (int i in restOfTheNumbers)
                {
                    result += i;
                }
            }
            Console.WriteLine("Total = " + result.ToString());
        }

        public static void Test(int a, int b = 10, int c = 20)
        {
            Console.WriteLine("a = " + a);
            Console.WriteLine("b = " + b);
            Console.WriteLine("c = " + c);
        }
    }
}
Output:

How to make method parameters optional in C#

How to make Parameter Optional Using OptionalAttribute in C#

Let us understand how to make method parameters optional by using the OptionalAttribute in C# that is present in System.Runtime.InteropServices namespace. Please have a look at the following function. Here, we decorate the third parameter with the Optional attribute which makes this parameter optional.

How to make Parameter Optional Using OptionalAttribute in C#

Here we are making the restOfTheNumbers optional by using the [Optional] attribute. Now, if we want to add just 2 numbers, then we can call the ADDNumbers method as shown below.
ADDNumbers(10, 20);
On the other hand, if you want to add 3 or more numbers, then you can invoke the method ADDNumbers() as shown below.
ADDNumbers(10, 20, new int[] { 30, 40 }); 

The complete example is given below.
using System;
using System.Runtime.InteropServices;

namespace OptionalParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            ADDNumbers(10, 20);        
            ADDNumbers(10, 20, new int[] { 30, 40, 50 });
           
            Console.ReadLine();
        }

        public static void ADDNumbers(int FN, int SN, [Optional] int[] restOfTheNumbers)
        {
            int result = FN + SN;
            // loop thru restOfTheNumbers only if it is not null otherwise 
            // you will get a null reference exception
            if (restOfTheNumbers != null)
            {
                foreach (int i in restOfTheNumbers)
                {
                    result += i;
                }
            }
            Console.WriteLine("Total = " + result.ToString());
        }
    }
}
Output:

How to make Parameter Optional Using OptionalAttribute in C#

In the next article, I am going to discuss how to create and use Indexers in C#Here, in this article, I try to explain how to make Optional Parameters in C# with examples. And I hope you enjoy this Optional Parameter in C# with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *