Named Parameters in C#

Named and optional arguments were introduced in C# 4.0 to provide developers the option to create named and optional parameters in a method.
 
Let's start reviewing some code.  
 
Listing 1 shows the AuthorRank class that defines and implements a CalculateRank method. The CalculateRank method takes three arguments of type short, double, and Boolean.
  1. public class AuthorRank  
  2. {  
  3. public double CalculateRank(short contributions, double loyalty, bool include)  
  4. {  
  5. if (include)  
  6. return (contributions * 0.12 + loyalty * 0.9);  
  7. return contributions * 0.12;  
  8. }  
  9. }  
Listing 1
 
The following code snippet calls the CalculateRank method where the first argument is a short value, the second argument is a double value and the third argument is a Boolean value.
  1. AuthorRank ar = new AuthorRank();  
  2. ar.CalculateRank(2, 2.3, true);  
Listing 2
 
So what happens if we do not pass the argument values in the same order as they are defined? For example, if we change the order of the values of parameters, we will get an error message from the compiler.
 
 
 
Thank Microsoft for Visual Studio IDE Intellisense and the compiler that tell us when the names and types of the parameters are incorrect. You may thank the reflection feature that reads Class Library DLL and lists its methods, their parameter names and their types.
 
What if you don’t have Visual Studio and are writing code in some editor that does not have Intellisense? What if we are calling an API such as a COM API that does not support reflection? What if we know parameter names only, without their order?
 
This is where you may find the named arguments or the named parameters feature useful.
 
Named arguments allow us to call a method without knowing the order of the parameters.
 
The named arguments of a method are defined using the parameter name followed by a colon and the parameter value. Once you define a method argument as named then no matter what order it is in, the compiler knows what it is and where to use the parameter value in what order.
 
The following code snippet uses named arguments to call the CaclulateRank method shown in Listing 1.
  1. AuthorRank ar = new AuthorRank();  
  2. ar.CalculateRank(include:true, contributions:2, loyalty:2.3);  
Listing 3
 
As you can see from the code above, the order of the method parameters is not the same as in the definition.
 
Summary
 
In this article, I demonstrated the meaning and purpose of named parameters in C#. If you’re writing general code, you may not need it but this is a useful weapon to have in your arsenal when writing complex libraries and applications.
 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.