CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Console.WriteLine("VB: OOP, multithreading, and more!");
break;
default:
Console.WriteLine("Well...good luck with that!");
break;
}
}
Note C# demands that each case (including default) that contains executable statements have a terminating
break or goto to avoid fall-through.
One nice feature of the C# switch statement is that you can evaluate string data in addition to
numeric data. Here is an updated switch statement that does this very thing (notice we have no need to
parse the user data into a numeric value with this approach).
static void SwitchOnStringExample()
{
Console.WriteLine("C# or VB");
Console.Write("Please pick your language preference: ");
string langChoice = Console.ReadLine();
switch (langChoice)
{
case "C#":
Console.WriteLine("Good choice, C# is a fine language.");
break;
case "VB":
Console.WriteLine("VB: OOP, multithreading and more!");
break;
default:
Console.WriteLine("Well...good luck with that!");
break;
}
}
It is also possible to switch on an enumeration data type. As you will see in Chapter 4, the C# enum
keyword allows you to define a custom set of name/value pairs. To whet your appetite, consider the
following final helper function, which performs a switch test on the System.DayOfWeek enum. You’ll notice
some syntax we have not yet examined, but focus on the issue of switching over the enum itself; the
missing pieces will be filled in over the chapters to come:
static void SwitchOnEnumExample()
{
Console.Write("Enter your favorite day of the week: ");
DayOfWeek favDay;
try
{
117