Named And Optional Parameter In C#

Introduction

Visual Studio 2010 (C# 4.0) introduced two new concepts Named and Optional Parameter which helps programmers to pass parameters with parameter name and omit some parameters to a method respectively. Let’s start the discussion.

Named Parameter

Named Parameter helps to pass parameters with parameter name to method. Generally we maintain parameters sequence when we pass parameters to a method. However in Named Parameter, it doesn’t need to maintain sequence while passing parameters to a method rather we can pass parameters with parameter name. Secondly, Parameter name should match with method definition parameter name.

For instance, AddNumber(int firstNumber, int secondNumber) is a method which takes two parameters and return sum of two numbers. Here firstNumber and secondNumber are two parameters we are passing to AddNumber() method using Named Parameter. If it doesn’t match the method definition parameter name and Named Parameter Name then it throws compilation error “The best overload for 'AddNumber' does not have a parameter named 'secondNumber1'”. The following method definition I will use in my future examples: 
  1. public static int AddNumber(int firstNumber, int secondNumber)  
  2. {  
  3.     return firstNumber+ secondNumber;  
  4. }  
We can call the method using Named Parameter: 
  1. AddNumber(firstNumber: 123, secondNumber: 64);  
Here are some cases that show the ways we can pass parameters and some points on Named Parameters:
 
Case 1: Using Normal Way
  1. AddNumber(12, 13);  
It is the normal way; mostly we use it in our code. But here we need to maintain the sequence of parameters. It means in above example firstNumber value will be 12 and secondNumber value will be 13.
 
Case 2: Using Named Parameter
  1. AddNumber(firstNumber: 12, secondNumber: 13);  
It is another way to pass parameters to a method. It is not mandatory to maintain parameter sequence as we are using named parameter concept. Here we are passing firstNumber as 12 and secondNumber as 13. We can write same code like:
  1. AddNumber(firstNumber: 12, secondNumber: 13);  
A parameter can be positional parameter as shown below:
  1. AddNumber(12, secondNumber: 13);  
Here we pass 12 as first parameter and 13 as second parameter.
 
But positional parameter doesn’t follow Named Parameter. It throws compilation error “Named argument specifications must appear after all fixed arguments have been specified”.
  1. AddNumber(firstNumber: 12, 13); // It will throw compilation error.  
Here is the complete code: 
  1. static void Main(string[] args)    
  2. {    
  3.   // The method can be called in the normal way, by using positional arguments.    
  4.   Console.WriteLine(AddNumber(12, 13));    
  5.     
  6.   // Named arguments can be supplied for the parameters in either order.    
  7.   Console.WriteLine(AddNumber(firstNumber: 12, secondNumber: 13));    
  8.   Console.WriteLine(AddNumber(secondNumber: 13, firstNumber: 12));    
  9.     
  10.   // Positional arguments cannot follow named arguments. It throws compilation error.
  11.   Console.WriteLine(AddNumber(firstNumber: 12, 13);    
  12.     
  13.   // Named arguments can follow positional arguments.    
  14.   Console.WriteLine(AddNumber(12, secondNumber: 13));    
  15. }    
Optional Parameter

In general meaning, Optional stands for it is not mandatory. Optional Parameter helps to omit parameters when we pass parameters to a method. Means it is not mandatory to pass all the parameters to a method. For instance there is a method called AddNumber(int firstNumber, int secondNumber) which takes two parameters and returns sum of two parameters. In general way, it is mandatory to pass two parameter values when we call the method. However Optional Parameter helps here and we can pass only zero/one/two parameters to the method.

It can be implemented in the following ways:

Option 1: Using Default Value

It is the normal and simple way to implement Optional Parameter. Here we need to define the default value of parameters in method definition. In the following code, secondNumber default value is “0”. So we can pass only one parameter to the method and complier will assume second parameter value “0” and return result as “12”. 
  1. namespace ConsoleApp2  
  2. {  
  3.     public class MyDemo  
  4.     {  
  5.         public int AddNumber(int firstNumber, int secondNumber = 0)  
  6.         {  
  7.             return firstNumber + secondNumber;  
  8.         }  
  9.   
  10.   
  11.         public void MainMethod()  
  12.         {  
  13.             AddNumber(12);  
  14.         }  
  15.     }  
  16. }  
VisualStudio IntelliSense uses Square bracket to indicate Optional Parameters. It is shown in the following figure:
 
Figure 1: VisualStudio shows IntelliSense to implement Optional Parameter 
 
Note: Default always need to define end of parameter list.
 
Option 2: Using OptionalAttribute
 
It is another way to implement the Optional Parameter using OptinalAttribute. To implement the same, we need to add namespace System.Runtime.InteropServices. Then we need to add “Optional” keyword surrounded with square bracket in front of method definition parameter. The “Optional” keyword presents in “Runtime.InteropServices” namespace. In the following example I defined second parameter (secondNumber) as optional; Compiler will consider “0” as default value. Optional attribute always need to define end of parameter list.
 
Here is the complete code:
  1. using System.Runtime.InteropServices;  
  2.   
  3. namespace ConsoleApp2  
  4. {  
  5.     public class MyDemo  
  6.     {  
  7.         public int AddNumber(int firstNumber, [Optional] int secondNumber)  
  8.         {  
  9.             return firstNumber + secondNumber;  
  10.         }  
  11.   
  12.         public void MainMethod()  
  13.         {  
  14.             AddNumber(12);  
  15.         }  
  16.     }  
  17. }  
Option 3: Using Method Overloading

It is another way to implement Optional Parameter concept. In Method Overloading we need to define different implementation with same method name and number of parameters are also different.

In the following code we defined two methods with same name (AddNumer) but different number of parameters. Firstly, AddNumber() method is taking only one parameter and second AddNumber() method is taking two parameters. When we call AddNumber() method with passing one parameter it will execute first AddNumber() method definition. And similarly when we pass two parameters it will execute second AddNumber() method definition.
 
Here is the complete code:
  1. namespace ConsoleApp2  
  2. {  
  3.     public class MyDemo  
  4.     {  
  5.         public int AddNumber(int firstNumber)  
  6.         {  
  7.             return firstNumber;  
  8.         }  
  9.   
  10.         public int AddNumber(int firstNumber, int secondNumber)  
  11.         {  
  12.             return firstNumber + secondNumber;  
  13.         }          
  14.   
  15.         public void MainMethod()  
  16.         {  
  17.             AddNumber(12);  
  18.             AddNumber(12, 13);  
  19.         }  
  20.     }  
  21. }  
Option 4: Using Params Keyword.

Using params we can pass variable number of parameters to a method and implement optional parameters concept.
 
There are some restrictions using the params keyword:
  • You can only use the params keyword for one parameter in your method declaration.
  • Params must be always the last parameter in method.
More on this visit here.
 
In the following example numbers is second parameter of AddNumber() which is of Integer Array type and we set “params” in front. Next move to MainMethod(). Firstly, we call AddNumber() with passing one parameter(12) which will be value of firstNumber parameter of AddNumber() definition. It will return result as “12”. Secondly, we call AddNumber() with passing two parameters(12, 13). “12” will be value of firstNumber and 13 will be value of numbers parameter. It will return result as “25”. Thirdly, we call AddNumber() with passing three parameters (12,13,14). “12” will be value of firstNumber and “13,14” will be value of numbers parameter. It will return result as “39”.
 
Here is the complete code:
  1. namespace ConsoleApp2  
  2. {  
  3.     public class MyDemo  
  4.     {  
  5.         public int AddNumber(int firstNumber, params int[] numbers)  
  6.         {  
  7.             int temp = 0;  
  8.             foreach (int tempNum in numbers)  
  9.             {  
  10.                 temp += tempNum;  
  11.             }  
  12.             return temp + firstNumber;  
  13.         }  
  14.   
  15.         public void MainMethod()  
  16.         {  
  17.             AddNumber(12); // Result: 12  
  18.             AddNumber(12, 13); // Result: 25  
  19.             AddNumber(12, 13, 14); // Result: 39  
  20.         }  
  21.     }  
  22. }  
Conclusion
 
In this article we discussed about what are Named and Optional Parameters in C#. Named arguments enable pass parameters with parameter name to a method rather than with the parameters sequence in the parameter list. Optional arguments enable you to omit arguments for some parameters when we call a method. We implemented Optional Parameters concepts in different ways: Default value, OptionalAttribute, Method Overloading and Params keyword. Option 3 & 4 are not purely Optional Parameters implementation; these are other ways to achieve the same. You can choose any of them as per your suitability.

Up Next
    Ebook Download
    View all
    FileInfo in C#
    Read by 9.7k people
    Download Now!
    Learn
    View all