C#
  Home arrow C# arrow Page 5 - Branching and Looping in C#, Part 1
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Moblin 
JMSL Numerical Library 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Branching and Looping in C#, Part 1
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 46
    2005-04-12

    Table of Contents:
  • Branching and Looping in C#, Part 1
  • No Implicit Conversion
  • Nesting
  • Combining else With if
  • The switch Statement
  • Looping Statements

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Branching and Looping in C#, Part 1 - The switch Statement


    (Page 5 of 6 )

    The switch statement is similar to multiple else if statements, but it accepts only expressions that will evaluate to constant values. The if/else structure is appropriate for small groups of Boolean expressions, but it would be very ugly to write 20 else if statements to test for some values: else if(x ==5) do something else if(x == 6) do another thing, and so on. This is the syntax of a switch statement:

    switch(expression)
    {
      case constant-value:
        statement 1;
        statement 2;
        jump statement
      case constant-value:
        statement 1;
        statement 2;
        jump statement
      default:
        statement 1;
        statement 2;
        jump statement
    }

    There are more than three keywords you can use with the switch statement: first, the switch keyword which, followed by an expression that returns an integral value of type sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an Enumeration value. The switch expression's value can be returned from a method call, too.

    After the switch expression is evaluated, the value will be compared to each case label, and when the value is found, control is transferred to the first statement in the this case statement. Each case statement must be ended with a jump statement (unlike C and C++), such as break or goto. The case keyword is used to define a constant value (called case label) that will be compared to the value returns from the switch expression. The constant value of the case label must have a compatible value with the switch block. This makes sense, because you can't define an int case label while the switch expression returns a string value. We will talk about jump statements later in the article.

    The default keyword declares the default statement, which will be executed if none of the case labels match the switch expression. There can be only one default statement for each switch statement, and you can write your switch statement without a default statement, too. Let's take a look at an example of a switch statement with our famous Employee class example:

    using System;
    namespace MyCompany
    {
      public enum Jobs
      {
        Programmer = 1,
        NetworkAdmin = 2,
        Designer = 3,
        COMDeveloper = 4
      }

      public class Employee
      {
        public Positions EmpJob;

          // class constructor
          public Employee(Jobs EJ)
          {
            switch(EJ)
            {
              case Jobs.Programmer:
                Console.WriteLine("You are a programmer");
                break;
              case Jobs.NetworkAdmin:
                Console.WriteLine("You are a network administrator");
                break;
              case Jobs.Designer:
                Console.WriteLine("You are a designer"); 
                break;
              default: 
                Console.WriteLine("You are an employee"); 
                break; 
            }
          } 
      }

      public class EmployeeTest
      {
        static void Main(string[] args)
          {
            Employee Michael = new Employee(Jobs.Designer);
            Console.ReadLine();
          }
      }
    }
     

    This is a very simple example. The Employee class constructor accepts a value of type Positions, and defines a switch case block to print the Employee job title. One very important issue to notice is that, with the if/else structure you can write as many else if statements, each with different conditional expressions, as you want -- but you can't do that with the switch/case structure. Here the case statements just test for the value of the switch expression, and if the comparison succeeds, the block get executed. If you have a statement that will be executed with more than one case label, you can combine case labels in the following way:

    switch(EP)
    {
      case Positions.Programmer:
      case Positions.NetworkAdmin:
      case Positions.Designer:
        Console.WriteLine("You are an IT Employee");
        break;
      default:
        Console.WriteLine("You are an employee");
        break;
    }

    You simply write a case statement followed by the next, until you write them all; then write the statement you want to be executed, then a jump statement. In C# you must use jump statements between case statements, because the designers of C# eliminated the fall though that has been in C and C++. You can still explicitly state that you need the functionality of fall though by using the goto jump keyword:

    switch(EP)
    {
      case Positions.Programmer:
        goto case Positions.Designer;
      case Positions.NetworkAdmin:
        goto case Positions.Designer;
      case Positions.Designer:
        Console.WriteLine("You are an IT Employee");
        break;
      default:
        Console.WriteLine("You are an employee");
      break;
    }

    This is an explicit fall through that is clear for every programmer and in fact this technique eliminates the common problems associated with fall through.

    More C# Articles
    More By Michael Youssef


     

    C# ARTICLES

    - Working with Regular Expressions in C#
    - Sending Simple E-Mail in C#
    - Building C# Comparable Objects: IComparable ...
    - Color Transformation Applications in C# GDI+...
    - Performing Color Transformation Operations i...
    - Color Transformation in C# GDI+ Programming
    - Exceptions in C#
    - Overriding versus Overloading
    - Value Types and Reference Types
    - Defining Member and Type Visibility
    - Managing Files in C#
    - Working with Windows Registry in C#
    - Lossless Image Resizing in C#
    - Lossless Image Converting in C#
    - Creating an RSS Feed with ASP.Net Written in...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway