Learning C# Part 3: Control Structures

Written By: Kevin Jordan

- 02 Sep 2006 -

Description: This series aims to take a beginning programmer to an intermediate level in C#. Topics covered in Part 3 include: if/else statements, switch/case, and for, while, and do loops.

  1. If, Else Condition Statements
  2. Switch Statements
  3. for Loops
  4. do and while Loops
  5. Aww Man... Not Homework

Switch Statements

Similar to the if statements, switch allows you to perform an action based on the value of a test. However, a switch statement also lets you test for multiple values of an expression rather than a single condition and can make your code more readable than using multiple if statements.

// x is an integer
switch (x)
{
        case 0:
                Console.Write("x is 0");
                break;
        case 1:
                Console.Write("x is 1");
                break;
        default:
                Console.Write("x is not 0 or 1");
                break;
}
 
// y is a string
switch (y)
{
        case "Yes":
                // perform yes actions
                break;
        case "No":
                // perform no actions
                break;
        default:
                // maybe actions
                break;
}

In the examples you'll notice a couple things. First, when you declare each case, you put a colon at the end. Each expression is evaluated, if the value matches then, the code block beneath is performed until it hits the break. If no values match, then the default behavior is performed. Defaults are not required, but should used so that an unexpected value will still be handled. Also, if you want the same action to occur for different values then you don't have to include a break. Here's an example:

// Create an enumeration type for the days of the week
enum DayOfWeek
{
        Sunday,
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday
}
 
// in here there will be code that assigns todaysDay as some value for the day of the week
 
switch (todaysDay)
{
        // perform the same action for weekends
        case DayOfWeek.Sunday:
        case DayOfWeek.Saturday:
                Console.Write("No work today");
                break;
        // perform the same action for weekdays
        case DayOfWeek.Monday:
        case DayOfWeek.Tuesday:
        case DayOfWeek.Wednesday:
        case DayOfWeek.Thursday:
        case DayOfWeek.Friday:
                Console.Write("Awe man, work today");
                break;
        default:
                break;
}

To me this looks a lot better than an if statement with a bunch of if this or this or this...

<< Previous

Next >>