The C Sharp switch Statement

From Techotopia
Revision as of 18:21, 16 January 2008 by Neil (Talk | contribs) (Using the switch Statement)

Jump to: navigation, search

In C# Flow Control Using if and else we looked at how to control program execution flow using the if and else statements. Whilst these statement constructs work well for a testing a limited number of conditions they quickly become unwieldy when dealing with larger numbers of possible conditions. To simplify these situations C# has inherited the switch statement from the C programming language. In this chapter we will explore the switch statement in detail.

Why Use a switch Statement?

For a small number of logical evaluations of a value the if .. else .. if construct outlined in C# Flow Control Using if and else is perfectly adequate. Unfortunately, any more than two or three possible scenarios can quickly make such a construct both time consuming to type and difficult to read. As a case in point consider the following code example. The program is designed to prompt a user for a car model and subsequently uses if .. else if ... statements to evaluate the car manufacturer:

using System;
using System.Text;

class Hello
{
        static void Main()
        {
                string carModel;
                string carManufacturer;

                System.Console.Write ("Please Enter Your Vehicle Model: ");

                myString = System.Console.ReadLine();

                if ((String.Compare(carModel, "Patriot") == 0) ||
                    (String.Compare(carModel, "Liberty") == 0) ||
                    (String.Compare(carModel, "Wrangler") == 0))
                {
                      carManufacturer = "Jeep";
                }
                else if (String.Compare(myString, "Focus") == 0)
                {
                      carManufacturer = "Ford";
                }
                else if (String.Compare(myString, "Corolla") == 0)
                {
                     carManufacturer = "Toyota";
                }
                else
                {
                     carManufacturer = "unknown";
                }

                System.Console.Write("Manufacturer is " + carManufacturer);
        }
}

As you can see, whilst the code is not too excessive it is already starting to become somewhat hard to read and also took more time to time than should really be necessary. Imagine, however, if instead of 3 car models we had to test for 10 or 20 models. Clearly an easier solution is needed, and that solution is the switch statement.

Using the switch Statement

The syntax for a C# switch statement is as follows:

 switch (value)
{ case constant:
statements
break/jump
case constant:
statements
break/jump
default:
statements
break/jump
}

This syntax needs a little explanation before we embark on creating a switch based version of the above if ... else construct.

In the above syntax outline value represents either a value or an expression which returns a value. This is the value against which the switch operate. Using our example this would be the string representing the car model.

For each possible match a case statement is required, followed by a constant value (once again using our example this would be the car manufacturers). Following on the the case line are the C# statements which are to be executed in the event of the value matching the case constant.

After the statements comes an optional break or goto statement. These statements are used either to break out of the switch statement when a match is found, or to goto a specific location in the code.

Finally, the default section of the construct defines what should happen if none of the case statements present a match to the value.

With this information in mind we may now construct a switch statement which provides the same functionality as our previous , and somewhat unwieldy if ... else construct: