Optional Parameter in C#

Introduction

This article explains the various ways to make method parameters optional. This is a very common interview question in C# Interview Questions.

There are following 4 ways to make method parameters optional.

  1. Using parameter arrays
  2. Using method overloading
  3. Using parameter defaults
  4. Using OptionalAttribute that is present in the System.Runtime.InteropServices namespace

Using parameter arrays

using System;

namespace OptionalParameter
{
    class Program
    {
        public static void Sum(int firstNumber, int secondNumber, params object[] restOfTheNumbers)
        {
            int result = firstNumber + secondNumber;
            foreach (int i in restOfTheNumbers)
            {
                result += i;
            }

            Console.WriteLine("Total = " + result.ToString());
        }

        public static void Main()
        {
            // Sum of two numbers
            Sum(10, 20);

            // Sum of more than two numbers
            Sum(10, 20, 30, 40, 50);
        }
    }
}

The Sum method allows us to add 2 or more numbers. The firstNumber and secondNumber parameters are mandatory, whereas the MoreNumbers parameter is optional.

Output

optonal param

Note. A parameter array must be the last parameter in a formal parameter list. The following method will not compile and gives a compile time error.

public static void Sum(int firstNumber, params object[] moreNumbers, int secondNumber)
{
    // Function implementation
}

Using method overloading

using System;

namespace OptionalParameter
{
    class Program
    {
        public static void Sum(int firstNumber, int secondNumber, int[] moreNumbers)
        {
            int result = firstNumber + secondNumber;
            if (moreNumbers != null)
            {
                foreach (int i in moreNumbers)
                {
                    result += i;
                }
            }

            Console.WriteLine("Sum = " + result);
        }

        public static void Sum(int firstNumber, int secondNumber)
        {
            int result = firstNumber + secondNumber;
            Console.WriteLine("Sum = " + result);
        }

        public static void Main()
        {
            // Sum of two Numbers
            Sum(10, 20);

            // Sum of more than two numbers
            Sum(10, 20, new int[] { 30, 40, 50 });
        }
    }
}

In the preceding example, I have two Sum methods that are overloaded or we can say there are 2 versions of the Sum method.

Output

method Overload

Parameters optional by specifying parameter defaults

using System;

namespace OptionalParameter
{
    class Program
    {
        public static void Sum(int firstNumber, int secondNumber, int[] moreNumbers = null)
        {
            int result = firstNumber + secondNumber;
            if (moreNumbers != null)
            {
                foreach (int i in moreNumbers)
                {
                    result += i;
                }
            }

            Console.WriteLine("Sum = " + result);
        }

        public static void Main()
        {
            // Sum of two Numbers
            Sum(10, 20);

            // Sum of more than two numbers
            Sum(10, 20, new int[] { 30, 40, 50 });
        }
    }
}

In the preceding example, I have set MoreNumbers=null by default and when I call Sum(10,20) then by default the value passed to MoreNumber=Null and when I call the same method like Sum(10,20, new int[]{30,40,50}) then it changes the default value.

Output

param dedfault

Example

using System;

namespace OptionalParameter
{
    class Program
    {
        public static void Test(int a, int b = 5, int c = 10)
        {
            Console.WriteLine("a = " + a);
            Console.WriteLine("b = " + b);
            Console.WriteLine("c = " + c);
        }

        public static void Main()
        {
            // a = 3, b = 5, c = 10
            Test(3);

            // a = 2, b = 3, c = 10
            Test(2, 3);

            // a = 5, b = 4, c = 6
            Test(5, 4, 6);
        }
    }
}

In the preceding example, the Test method contains the 3 parameters a, b, c but we have set b=5 and c=10 so here a parameter will be a required parameter and b and c are optional parameters.

test method

Note. Optional parameters must appear after all the required parameters, in other words the following method will not compile.

Assigning a value to a specific optional parameter

The following sample shows how to assign a value to a specific optional parameter

using System;

namespace OptionalParameter
{
    class Program
    {
        public static void Test(int a, int b = 5, int c = 10)
        {
            Console.WriteLine("a = " + a);
            Console.WriteLine("b = " + b);
            Console.WriteLine("c = " + c);
        }

        public static void Main()
        {
            
            Test(3);
            Console.WriteLine();
            Test(2, c: 3);
        }
    }
}

Output

example 2

Making method parameters optional using Optional Attribute

In this example, we will discuss OptionalAttribute in the System.Runtime.InteropServices namespace.

using System;
using System.Runtime.InteropServices;

namespace OptionalParameter
{
    class Program
    {
        public static void Sum(int firstNumber, int secondNumber, [Optional] int[] moreNumbers)
        {
            int result = firstNumber + secondNumber;
            if (moreNumbers != null)
            {
                foreach (int i in moreNumbers)
                {
                    result += i;
                }
            }
            Console.WriteLine("Sum = " + result);
        }

        public static void Main()
        {
            // Sum of two Numbers
            Sum(10, 20);

            // Sum of more than two numbers
            Sum(10, 20, new int[] { 30, 40, 50 });
        }
    }
}

In the preceding example, we have a method Sum where two parameters are required, firstNumber and secondNumber, but the last parameter MoreNumber I have marked as an [Optional] attribute.

Output

addtional attribute

Thank you. Happy Coding


Similar Articles