Home > Articles

This chapter is from the book

This chapter is from the book

7.14 Named Parameters

Normally, when calling a method, the argument values—in order—are assigned to the parameters from left to right in the parameter list. Consider a Time class that stores the time of day in 24-hour clock format as int values representing the hour (0–23), minute (0–59) and second (0–59). Such a class might provide a SetTime method with optional parameters like

public void SetTime(int hour = 0, int minute = 0, int second = 0)

In the preceding method header, all three of SetTime’s parameters are optional. Assuming that we have a Time object named t, consider the following calls to SetTime:

  • t.SetTime()—This call specifies no arguments, so the compiler assigns the default value 0 to each parameter. The resulting time is 12:00:00 AM.

  • t.SetTime(12)—This call specifies the argument 12 for the first parameter, hour, and the compiler assigns the default value 0 to the minute and second parameters. The resulting time is 12:00:00 PM.

  • t.SetTime(12, 30)—This call specifies the arguments 12 and 30 for the parameters hour and minute, respectively, and the compiler assigns the default value 0 to the parameter second. The resulting time is 12:30:00 PM.

  • t.SetTime(12, 30, 22)—This call specifies the arguments 12, 30 and 22 for the parameters hour, minute and second, respectively, so the compiler does not provide any default values. The resulting time is 12:30:22 PM.

    What if you wanted to specify only arguments for the hour and second? You might think that you could call the method as follows:

t.SetTime(12, , 22); // COMPILATION ERROR

C# doesn’t allow you to skip an argument as shown above. C# provides a feature called named parameters, which enable you to call methods that receive optional parameters by providing only the optional arguments you wish to specify. To do so, you explicitly specify the parameter’s name and value—separated by a colon (:)—in the argument list of the method call. For example, the preceding statement can be written as follows:

t.SetTime(hour: 12, second: 22); // sets the time to 12:00:22

In this case, the compiler assigns parameter hour the argument 12 and parameter second the argument 22. The parameter minute is not specified, so the compiler assigns it the default value 0. It’s also possible to specify the arguments out of order when using named parameters. The arguments for the required parameters must always be supplied. The argumentName: value syntax may be used with any method’s required parameters.

  • + Share This
  • 🔖 Save To Your Account