Home > Articles

This chapter is from the book

This chapter is from the book

7.13 Optional Parameters

Methods can have optional parameters that allow the calling method to vary the number of arguments to pass. An optional parameter specifies a default value that’s assigned to the parameter if the optional argument is omitted. You can create methods with one or more optional parameters. All optional parameters must be placed to the right of the method’s non-optional parameters—that is, at the end of the parameter list.

When a parameter has a default value, the caller has the option of passing that particular argument. For example, the method header

static int Power(int baseValue, int exponentValue = 2)

specifies an optional second parameter. Each call to Power must pass at least a baseValue argument, or a compilation error occurs. Optionally, a second argument (for the exponentValue parameter) can be passed to Power. Each optional parameter must specify a default value by using an equal (=) sign followed by the value. For example, the header for Power sets 2 as exponentValue’s default value. Consider the following calls to Power:

  • Power()—This call generates a compilation error because this method requires a minimum of one argument.

  • Power(10)—This call is valid because one argument (10) is being passed. The optional exponentValue is not specified in the method call, so the compiler uses 2 for the exponentValue, as specified in the method header.

  • Power(10, 3)—This call is also valid because 10 is passed as the required argument and 3 is passed as the optional argument.

Figure 7.14 demonstrates an optional parameter. The program calculates the result of raising a base value to an exponent. Method Power (lines 15–25) specifies that its second parameter is optional. In Main, lines 10–11 call method Power. Line 10 calls the method without the optional second argument. In this case, the compiler provides the second argument, 2, using the default value of the optional argument, which is not visible to you in the call.

 1   // Fig. 7.14: CalculatePowers.cs
 2   // Optional parameter demonstration with method Power.
 3   using System;
 5   class CalculatePowers
 6   {
 7      // call Power with and without optional arguments
 8      static void Main()
 9      {
10         Console.WriteLine($"Power(10) = {Power(10)}") ;
11         Console.WriteLine($"Power(2, 10) = {Power(2, 10)}");
12      }
14      // use iteration to calculate power
15      static int Power(int baseValue, int exponentValue = 2)
16      {
17         int result = 1;
19         for (int i = 1; i <= exponentValue; ++i)
20         {
21            result *= baseValue;
22         }
24         return result;
25      }
26   }
Power(10) = 100
Power(2, 10) = 1024

Fig. 7.14 | Optional parameter demonstration with method Power.

  • + Share This
  • 🔖 Save To Your Account