Difference between revisions of "The C Sharp switch Statement"

From Techotopia
Jump to: navigation, search
(Using the switch Statement)
(Using the switch Statement)
Line 45: Line 45:
 
The syntax for a C# ''switch'' statement is as follows:
 
The syntax for a C# ''switch'' statement is as follows:
  
   switch (''expression'')<br>
+
   switch (''value'')<br>
 
   {
 
   {
 
       case ''constant'':<br>
 
       case ''constant'':<br>

Revision as of 21:32, 15 January 2008

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 myString = "Fred";

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

                myString = System.Console.ReadLine();

                if (String.Compare(myString, "Patriot") == 0)
                {
                     System.Console.WriteLine ("Manufactured by Jeep");
                }
                else if (String.Compare(myString, "Focus") == 0)
                {
                     System.Console.WriteLine ("Manufactured by Ford");
                }
                else if (String.Compare(myString, "Corolla") == 0)
                {
                     System.Console.WriteLine ("Manufactured by Toyota");
                }
                else
                {
                     System.Console.WriteLine ("Vehicle model not recognized!");
                }
        }
}

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 of explanation.