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.
- public class AuthorRank
- {
- public double OptionalParameterMethod(short contributions, double loyalty = 3.1, bool include = true)
- {
- if (include)
- return (contributions * 0.12 + loyalty * 0.9);
- return contributions * 0.12;
- }
- }
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.
- AuthorRank ar = new AuthorRank();
- Console.WriteLine(ar.OptionalParameterMethod(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.