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.
- Using parameter arrays
- Using method overloading
- Using parameter defaults
- 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

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




Prabu ElavarasanPosted Apr 11, 2019, 12:10 AM
Is this Optional keyword works with REF & OUT properties?? Because in called method we cannot user ref int x=null right? Like said, is this rule applicable for Optional keyword as well?
Guest UserPosted Nov 17, 2014, 8:26 AM
cool. simple & clear explanation!
Keyur PatelPosted Nov 17, 2014, 5:56 AM
Nice explanation.
Vithal WadjePosted Nov 17, 2014, 4:46 AM
good one