Working with The Switch Statement

It’s relatively common to come across a situation in which you want to check one variable for a number of possible values. You can use the if…else if structure for these situations, but C# supplies a handy structure that specializes in these kinds of scenarios: the switch statement. In such situations, you use the switch statement, which I’ll explain a little later, but for now take a look at the Switch Demo program, which will ease you into switch statements.

The Switch Demo Program

Look at the following source code for an illustration of the switch statement:

using System;

namespace SwitchDemo
{
  /// <summary>
  /// Demonstrates use of the Switch structure
  /// Andy Harris, 11/10/01
  /// </summary>
  class SwitchDemo
  {
    static void Main(string[] args)
    {
      string fullName;
      string greeting;

      //get name from user
      Console.Write("Please Enter your full name: ");
      fullName = Console.ReadLine();

      //check name
      switch (fullName){
        case "Bill Gates":
          greeting = "Great job on C#";
          break;
        case "James Gosling":
          greeting = "That Java thing is really cool";
          break;
        case "Alan Turing":
          greeting = "The Turing machine was pretty amazing";
          break;
        case "Grace Hopper":
          greeting = "Wow. You discovered the first computer bug!";
          break;
        default:
          greeting = "We're waiting for your contribution to computer science,
" + fullName;
          break;
      } // end switch

       //write response
       Console.WriteLine(greeting); 
    Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine("Press "enter" to continue");
    Console.ReadLine();
  } // end main
 } // end class
} // end namespace

Examining How Switch Statements Work

The switch statement looks at one variable or expression (in this case, the variable fullName) and compares it to several cases. In essence, this code

switch (fullName){
         case "Bill Gates":
           greeting = "Great job on C#";
           break;

is equivalent to the following code, which contains a switch statement:

if (fullName == "Bill Gates")
{
  greeting = "Great job on C#";
}

The variable you are comparing belongs in a pair of parentheses right after the keyword switch. The rest of the structure goes inside a pair of braces. For each value you want to compare, you build a case structure. This structure describes the value you are comparing the variable to. For example, “Bill Gates” is one possible value of userName, and “James Gosling” is another, so each of these terms makes up a case. The case structure begins with the keyword case, followed by the value you want to compare and then a colon (:) character. You must end each case with a break statement, which informs the computer that you are finished considering this possible value for the expression. The break structure helps the computer understand that you are done writing code that should happen if the user is Bill Gates, for example, and you’re ready to start the next case (which might be James Gosling).

If you are familiar with another programming language, take a careful look at the switch statement. In C#, the switch statement differs from its cousins in the other popular languages. It is possible to switch on a string variable (this is impossible in C), and C# requires the break statement at the end of each case, unlike Visual Basic or C.

The switch statement has a section named default:, which acts like the else clause in an if structure. If none of the other cases turn out to be true, the code in the else clause executes. It’s a good idea to include a default clause in any switch statement you build.

If you want to see what’s going on in your code, you can step through it one line at a time. While you are in the IDE (Integrated Debugging Environment), press F11 to run one line of code. You will see the current line of code highlighted in yellow. Keep pressing the F11 key to see how the computer walks through your code and how it skips over elements. This is a great way to see how branching structures work.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.10.32