C# 4.0 - Named Parameters

Introduction

 
C# 4.0 has introduced a number of interesting features which includes Optional Parameters, Default Values, and Named Parameters.Functions with same name and different parameters (function overloading) If we have a function,
  1. public class Test  
  2. {  
  3.         public void Print( int num1, num num2, num num3)  
  4.         {  
  5.             Console.WriteLine("{0},{1},{2}", num1, num2, num3);  
  6.         }  
  7. }  
This has three parameters. How do we use it in the main function,
  1. Test testClass = new Test();   
  2. testClass.Print(10, 12,14);  
Suppose we require three different functions with same name and accepts different parameters (function overloading), to use in different scenario. The code will be,
  1. public class Test {  
  2.     public void Print(int num3) {  
  3.         Print(10, 12, num3);  
  4.     }  
  5.     public void Print(int num2, int num3) {  
  6.         Print(10, num2, num3);  
  7.     }  
  8.     public void Print(int num1, double num2, string str) {  
  9.         Console.WriteLine("{0},{1},{2}", str, num1, num2);  
  10.     }  
  11. }  

Optional Parameters


You can provide optional values to the parameters. You can use these default values or give your own value, thereby can reduce the overhead of multiple functions. Then the values can be given as,
  1. public class Test {  
  2.     public Test(string someValue = "testValue")  
  3.     //default values can be assigned for the constructor parameters also  
  4.     {}  
  5.     public void Print(int num1 = 5, int num2 = 10, int num3 = 15) {  
  6.         Console.WriteLine("{0},{1},{2}", num1, num2, num3);  
  7.     }  
  8. }  
Suppose we want the default value of only the last integer value then also we can call the function as,
  1. Test testClass = new Test();  
  2. testClass.Print(10, 12);  

Named Parameters

 
Suppose you want to change the third parameter value and have the default for second. Can you do it like this,
  1. testClass.Print(10, 12);  
No the compiler misunderstand it to be num2. So we'll have to specify for which we use Named Parameters
  1. testClass.Print(10, num3:12);  
The new syntax '[parameter]:' is a very attractive achievement of C# 4.0 The convention with optional parameters is that optional parameters must come at the end of the list of method arguments. Hence, you specify all your required arguments in the method first and then list the optional arguments last just like we did above.


Similar Articles