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

Praveen NPosted Feb 12, 2014, 8:08 AM
Good one :)