O'Reilly logo

Microsoft® Visual C#® 2008 Step by Step by John Sharp

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using switch Statements

Sometimes when you write a cascading if statement, all the if statements look similar because they all evaluate an identical expression. The only difference is that each if compares the result of the expression with a different value. For example, consider the following block of code that uses an if statement to ine the value in the day variable and work out which day of the week it is:

if (day == 0)
    dayName = "Sunday";
else if (day == 1)
    dayName = "Monday";
else if (day == 2)
    dayName = "Tuesday";
else if (day == 3)
    ...
else
    dayName = "Unknown";

In these situations, often you can rewrite the cascading if statement as a switch statement to make your program more efficient and more readable.

Understanding switch Statement Syntax ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required