Optional 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.   

Optional arguments allow developers to write methods that have optional parameters. Each optional parameter has a default value. If the caller code does not pass a value of the optional parameter, the default value is used.

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.

Let’s have a look at the code in Listing 1. 

  1. public class AuthorRank  
  2. {  
  3. public double OptionalParameterMethod(short contributions, double loyalty = 3.1, bool include = true)  
  4. {  
  5. if (include)  
  6. return (contributions * 0.12 + loyalty * 0.9);  
  7. return contributions * 0.12;  
  8. }  
  9. }  

Listing 1

In Listing 1, the OptionalParameterMethod has its last two parameters optional and the caller code does not need to pass a value for these parameters.

The following code snippet calls the OptionalParameterMethod in two different ways. The first call does not specify any value for the optional parameters. The second call on the other hand passes the optional parameter values. 

  1. AuthorRank ar = new AuthorRank();  
  2. Console.WriteLine(ar.OptionalParameterMethod(3));  
  3. Console.WriteLine(ar.OptionalParameterMethod(3, 4.4, true));  

Summary

In this article, I demonstrated the meaning and purpose of optional 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.