CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
// This is OK, as positional args are listed before named args.
DisplayFancyMessage(ConsoleColor.Blue,
message: "Testing...",
backgroundColor: ConsoleColor.White);
// This is an ERROR, as positional args are listed after named args.
DisplayFancyMessage(message: "Testing...",
backgroundColor: ConsoleColor.White,
ConsoleColor.Blue);
This restriction aside, you might still be wondering when you would ever want to use this language
feature. After all, if you need to specify three arguments to a method, why bother flipping around their
position?
Well, as it turns out, if you have a method that defines optional arguments, this feature can actually
be really helpful. Assume DisplayFancyMessage() has been rewritten to now support optional
arguments, as you have assigned fitting defaults:
static void DisplayFancyMessage(ConsoleColor textColor = ConsoleColor.Blue,
ConsoleColor backgroundColor = ConsoleColor.White,
string message = "Test Message")
{
...
}
Given that each argument has a default value, named arguments allow the caller to specify only the
parameter(s) for which they do not wish to receive the defaults. Therefore, if the caller wants the value
"Hello!" to appear in blue text surrounded by a white background, they can simply specify:
DisplayFancyMessage(message: "Hello!");
Or, if the caller wants to see “Test Message” print out with a green background containing blue text,
they can invoke DisplayFancyMessage():
DisplayFancyMessage(backgroundColor: ConsoleColor.Green);
As you can see, optional arguments and named parameters do tend to work hand in hand. To wrap
up our examination of building C# methods, I need to address the topic of method overloading.
Source Code The FunWithMethods application is located under the Chapter 4 subdirectory.
Understanding Method Overloading
Like other modern object-oriented languages, C# allows a method to be overloaded. Simply put, when
you define a set of identically named methods that differ by the number (or type) of parameters, the
method in question is said to be overloaded.
To understand why overloading is so useful, consider life as an old-school Visual Basic 6.0 (VB6)
developer. Assume you are using VB6 to build a set of methods that return the sum of various incoming
data types (Integers, Doubles, and so on). Given that VB6 does not support method overloading, you
w