Named And Optional Parameters In C#

This article explains Named and Optional Parameters in C#, their usages and benefits, and how to pass optional parameters in C#.

Introduction

 
C# 4.0 introduced two new concepts, Named parameters and Optional parameters. In this article and code examples, let's see how we can use and take advantages of named parameters adn optional parameters in C# and .NET. 
 

Named Parameter

 
Named Parameters allow developers to pass a method arguments with parameter names. Prior to these this feature, the method parameters were passed using a sequence only. Now, using named parameters in C#, we can put any parameter in any sequence as long as the name is there. The right parameber value based on their names will be mapped to the right variable. The parameters name must match with the method definition parameter names.
 
The syntax of parameter names is (parametername: value). 
 
In the following code example, the method AddNumber(int firstNumber, int secondNumber) takes two parameters and returns a sum of the two numbers. Here, firstNumber and secondNumber are two parameters that are passed in AddNumber() method using named parameters. 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 also use in my following examples.
  1. public static int AddNumber(int firstNumber, int secondNumber)  
  2. {  
  3.     return firstNumber+ secondNumber;  
  4. }  
To call the above method, we use the following method call. As you can see from this below code snippet, the name of the parameter is used with a ":" followed by the value. 
  1. AddNumber(firstNumber: 123, secondNumber: 64);  
Here are some cases that show how to pass parameters in a method.
Case 1: Using Normal Way
  1. AddNumber(12, 13);  
Thi is the way we usually call methods. In this case, the value of the parameters are passed to the arguments in same order. In this case, the order of the parameters in the call must be exactly same as in the method definition. It means in above example, firstNumber value will be 12 and secondNumber value will be 13.
 
Case 2: Using Named Parameters
  1. AddNumber(firstNumber: 12, secondNumber: 13);  
It is another way to pass parameters to a method. It is not mandatory to keep the parameter sequence because we are using named parameters. Regardless of the order of the parameters, the value of the agument will be matched based on their names. 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 parameters doesn’t follow Named Parameters. 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 C# code shows how to use named parameters.
  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 Parameters

 
By default, all parameters of a method are required. But in C# 4.0, the concept of optional parameters was introduced that allows developers to declare parameters as optional. That means, if these arguments are not passed, they will be ommitted from the execution. Optional parameters are not mandatory.
 
For instance, there is a method called AddNumber(int firstNumber, int secondNumber) which takes two parameters and returns the sum of two parameters. By default, it is mandatory to pass both parameter values when we call the method. However Optional Parameters allow us not to pass these values.
 
It can be implemented in the following ways:
 
Option 1: Using Default Values
 
It is the common way to implement Optional Parameters. Here we need to set the default values of the parameters in the method definition. In the following code snippet, secondNumber default value is “0”. So we can pass one parameter to the method only and the complier will assume the second parameter value “0”. The method will return the 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:
 
Optional Parameter in C# 
Figure 1: VisualStudio shows IntelliSense to implement Optional Parameter 
 
Note: Default values always need to define in the end of the parameters list.
 
Option 2: Using OptionalAttribute
 
There is another way to implement Optional Parameters, i.e., using the OptinalAttribute. To implement this, we need to import System.Runtime.InteropServices namespace. Then we need to add “Optional” keyword surrounded with the square bracket in the front of the method definition parameter. The “Optional” keyword is defined in the “Runtime.InteropServices” namespace.
 
In the following example, I define the second parameter (secondNumber) as optional; Compiler will consider “0” as default value. Optional attribute always need to be defined in the end of the parameters 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
 
One more ways we can implement optional parameters is using method overloading. Method overloading allows us to create multiple definitions of same method with different parameters. If you're new to method overloading, read Method Overloading In C#.
 
In the following code, we've defined two methods with same names (AddNumer) but different number of parameters. First, AddNumber() method takes only one parameter and second AddNumber() method takes two parameters. When we call AddNumber() method with one parameter only, the compiler will execute the first AddNumber() method. And similarly when we pass two parameters, the compiler will execute the second AddNumber() method.
 
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 a 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 Using Params in C#.
 
In the following example, numbers is the second parameter of AddNumber(), which is of type Integer Array type using “params”. The array items can be accessed using the array items index. 
 
You can see, we have three different calls of the AddNumber method and values are read back and added to the result. In the first call, we call AddNumber() with one parameter(12) only and the restult will be 12. In the second call, we call AddNumber() with two parameters(12, 13). The result will be 25. In the thrid case, we pass three parameters (12,13,14). The result will be 39. 
 
Here is the C# complete code example:
  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 Named and Optional Parameters in C#. We also saw different examples of these features of C#.