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.
Declaring a non-optional parameter to the right of an optional one is a compilation error.
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.15 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.