Home

Case Switches

 

Introduction

When defining an expression whose result would lead to a specific program execution, the switchC# Collections- A Collection of Items statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: { to }. The syntax of the switch statement is:

switch(Expression)
{
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
}
 
Author Note In C++, you can omit the break keyword in a case. This creates the "fall through" effect as follows: after code executes in a case, if nothing "stops" it, the execution continues to the next case. This has caused problems and confusing execution in the past in some C++ programs. To avoid it, C# requires code interruption at the end of every case. This interruption is done using the break keyword.

The expression to examine in a case statement is an integer. Since a member of an enumerator (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

class Program
{
    static void Main()
    {
        HouseType type = HouseType.Unknown;
        int choice;
        string strGarage = "";

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1. Single Family");
        Console.WriteLine("2. Townhouse");
        Console.WriteLine("3. Condominium");
        Console.Write("You Choice? ");
        choice = int.Parse(Console.ReadLine());

        switch (choice)
        {
            case 1:
                type = HouseType.SingleFamily;
                break;

            case 2:
                type = HouseType.Townhouse;
                break;

            case 3:
                type = HouseType.Condominium;
                break;
        }

        Console.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
        int ans = int.Parse(Console.ReadLine());
        if (ans == 1)
            strGarage = "Yes";
        else
            strGarage = "No";

        Console.WriteLine("\nDesired House Type: {0}", type);
        Console.WriteLine("Has indoor garage?  {0}", strGarage);
    }
}

When establishing the possible outcomes that the switch statement should consider, at times there will be possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:

switch(Expression)
{
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
    default:
         Other-Possibility;
	break;
}
In C++, the default section doesn't need a break keyword because it is the last. In C#, every case and the default section must have its own exit mechanism, which is taken care of by a break keyword.

Therefore another version of the program above would be

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

class Program
{
    static void Main()
    {
        HouseType type = HouseType.Unknown;
        int choice;
        string strGarage = "";

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1. Single Family");
        Console.WriteLine("2. Townhouse");
        Console.WriteLine("3. Condominium");
        Console.Write("You Choice? ");
        choice = int.Parse(Console.ReadLine());

        switch (choice)
        {
            case 1:
                type = HouseType.SingleFamily;
                break;

            case 2:
                type = HouseType.Townhouse;
                break;

            case 3:
                type = HouseType.Condominium;
                break;

            default:
                type = HouseType.Unknown;
                break;
        }

        Console.Write("Does the house have an indoor garage (1=Yes/0=No)? ");
        int ans = int.Parse(Console.ReadLine());
        if (ans == 1)
            strGarage = "Yes";
        else
            strGarage = "No";

        Console.WriteLine("\nDesired House Type: {0}", type);
        Console.WriteLine("Has indoor garage?  {0}", strGarage);
    }
}

Here is an example of running the program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 8
Does the house have an indoor garage (1=Yes/0=No)? 2

Desired House Type: Unknown
Has indoor garage?  No
Press any key to continue . . .

Besides a value of an int type, you can also use another variant of integers on a switch statement. For example, you can use letters to validate the cases. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

class Program
{
    static void Main()
    {
        HouseType type = HouseType.Unknown;
        int choice;
        string strGarage = "";

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1. Single Family");
        Console.WriteLine("2. Townhouse");
        Console.WriteLine("3. Condominium");
        Console.Write("You Choice? ");
        choice = int.Parse(Console.ReadLine());

        switch (choice)
        {
            case 1:
                type = HouseType.SingleFamily;
                break;

            case 2:
                type = HouseType.Townhouse;
                break;

            case 3:
                type = HouseType.Condominium;
                break;

            default:
                type = HouseType.Unknown;
                break;
        }

        Console.Write("Does the house have an indoor garage (y/n)? ");
        char ans = char.Parse(Console.ReadLine());
        switch (ans)
        {
            case 'y':
                strGarage = "Yes";
                break;

            case 'n':
                strGarage = "No";
                break;

            default:
                strGarage = "Not Specified";
                break;
        }

        Console.WriteLine("\nDesired House Type: {0}", type);
        Console.WriteLine("Has indoor garage?  {0}", strGarage);
    }
}

Here is an example of running the program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Does the house have an indoor garage (y/n)? y

Desired House Type: Condominium
Has indoor garage?  Yes
Press any key to continue . . .

 

Practical LearningPractical Learning: Introducing Boolean Variables

  1. To create a new class, in the Solution Explorer, right-click the project name, position the mouse on Add and click Class...
  2. Set the Name of the class to OrderProcessing and click Add
  3. Complete the OrderProcessing.cs file as follows:
     
    using System;
    
    namespace FlowerShop2
    {
        class OrderProcessing
        {
            public Flower FlowerOrder;
            public int Quantity;
    
            public OrderProcessing()
            {
                FlowerOrder = new Flower();
            }
    
            public decimal GetTotalPrice()
            {
                return Quantity * FlowerOrder.UnitPrice;
            }
    
            public void GetFlowerType()
            {
                int choice = 0;
    
                Console.WriteLine("Enter the Type of Flower Order");
                Console.WriteLine("1. Roses");
                Console.WriteLine("2. Lilies");
                Console.WriteLine("3. Daisies");
                Console.WriteLine("4. Carnations");
                Console.WriteLine("5. Live Plant");
                Console.WriteLine("6. Mixed");
                Console.Write("Your Choice: ");
                choice = int.Parse(Console.ReadLine());
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Type = FlowerType.Roses;
                        break;
                    case 2:
                        FlowerOrder.Type = FlowerType.Lilies;
                        break;
                    case 3:
                        FlowerOrder.Type = FlowerType.Daisies;
                        break;
                    case 4:
                        FlowerOrder.Type = FlowerType.Carnations;
                        break;
                    case 5:
                        FlowerOrder.Type = FlowerType.LivePlant;
                        break;
                    default:
                        FlowerOrder.Type = FlowerType.Mixed;
                        break;
                }
            }
    
            public void GetFlowerColor()
            {
                int choice = 0;
    
                Console.WriteLine("Enter the Color");
                Console.WriteLine("1. Red");
                Console.WriteLine("2. White");
                Console.WriteLine("3. Yellow");
                Console.WriteLine("4. Pink");
                Console.WriteLine("5. Orange");
                Console.WriteLine("6. Blue");
                Console.WriteLine("7. Lavender");
                Console.WriteLine("8. Mixed");
                Console.Write("Your Choice: ");
                choice = int.Parse(Console.ReadLine());
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Color = FlowerColor.Red;
                        break;
                    case 2:
                        FlowerOrder.Color = FlowerColor.White;
                        break;
                    case 3:
                        FlowerOrder.Color = FlowerColor.Yellow;
                        break;
                    case 4:
                        FlowerOrder.Color = FlowerColor.Pink;
                        break;
                    case 5:
                        FlowerOrder.Color = FlowerColor.Yellow;
                        break;
                    case 6:
                        FlowerOrder.Color = FlowerColor.Blue;
                        break;
                    case 7:
                        FlowerOrder.Color = FlowerColor.Lavender;
                        break;
                    default:
                        FlowerOrder.Color = FlowerColor.Mixed;
                        break;
                }
            }
    
            public void GetFlowerArrangement()
            {
                int choice = 0;
    
                Console.WriteLine("Enter the Type of Arrangement");
                Console.WriteLine("1. Bouquet");
                Console.WriteLine("2. Vase");
                Console.WriteLine("3. Basket");
                Console.WriteLine("4. Mixed");
                Console.Write("Your Choice: ");
                choice = int.Parse(Console.ReadLine());
    
                switch (choice)
                {
                    case 1:
                        FlowerOrder.Arrangement = FlowerArrangement.Bouquet;
                        break;
                    case 2:
                        FlowerOrder.Arrangement = FlowerArrangement.Vase;
                        break;
                    case 3:
                        FlowerOrder.Arrangement = FlowerArrangement.Basket;
                        break;
                    default:
                        FlowerOrder.Arrangement = FlowerArrangement.Any;
                        break;
                }
            }
    
            public void ProcessOrder()
            {
                GetFlowerType();
                GetFlowerColor();
                GetFlowerArrangement();
    
                Console.Write("Enter the Unit Price: ");
                FlowerOrder.UnitPrice = decimal.Parse(Console.ReadLine());
    
                Console.Write("Enter Quantity:       ");
                Quantity = int.Parse(Console.ReadLine());
            }
    
            public void ShowOrder()
            {
                Console.WriteLine("=======================");
                Console.WriteLine("==-=-=Flower Shop=-=-==");
                Console.WriteLine("-----------------------");
                Console.WriteLine("Flower Type:  {0}", FlowerOrder.Type);
                Console.WriteLine("Flower Color: {0}", FlowerOrder.Color);
                Console.WriteLine("Arrangement:  {0}", FlowerOrder.Arrangement);
                Console.WriteLine("Price:        {0:C}", FlowerOrder.UnitPrice);
                Console.WriteLine("Quantity:     {0}", Quantity);
                Console.WriteLine("Total Price:  {0:C}", GetTotalPrice());
                Console.WriteLine("=======================");
            }
        }
    }
  4. Access the Program.cs file and complete it as follows:
     
    using System;
    
    namespace FlowerShop2
    {
        class Program
        {
            static void Main()
            {
                OrderProcessing order = new OrderProcessing();
    
                order.ProcessOrder();
                Console.WriteLine();
    
                order.ShowOrder();
                Console.WriteLine();
            }
        }
    }
  5. Execute the application and test it. Here is an example:
     
    Enter the Type of Flower Order
    1. Roses
    2. Lilies
    3. Daisies
    4. Carnations
    5. Live Plant
    6. Mixed
    Your Choice: 4
    Enter the Color
    1. Red
    2. White
    3. Yellow
    4. Pink
    5. Orange
    6. Blue
    7. Lavender
    8. Mixed
    Your Choice: 7
    Enter the Type of Arrangement
    1. Bouquet
    2. Vase
    3. Basket
    4. Mixed
    Your Choice: 3
    Enter the Unit Price: 45.85
    Enter Quantity:       3
    
    =======================
    ==-=-=Flower Shop=-=-==
    -----------------------
    Flower Type:  Carnations
    Flower Color: Lavender
    Arrangement:  Basket
    Price:        $45.85
    Quantity:     3
    Total Price:  $137.55
    =======================
    
    Press any key to continue . . .
  6. Close the DOS window

Combining Cases

Each of the cases we have used so far examined only one possibility before executing the corresponding statement. You can combine cases to execute the same statement. To do this, type a case, its value, and the semi-colon. Type another case using the same formula. When the cases are ready, you can then execute the desired statement. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

class Program
{
    static void Main()
    {
        HouseType type = HouseType.Unknown;
        int choice;
        string strGarage = "";

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1. Single Family");
        Console.WriteLine("2. Townhouse");
        Console.WriteLine("3. Condominium");
        Console.Write("You Choice? ");
        choice = int.Parse(Console.ReadLine());

        switch (choice)
        {
            case 1:
                type = HouseType.SingleFamily;
                break;

            case 2:
                type = HouseType.Townhouse;
                break;

            case 3:
                type = HouseType.Condominium;
                break;

            default:
                type = HouseType.Unknown;
                break;
        }

        Console.Write("Does the house have an indoor garage (y/n)? ");
        char ans = char.Parse(Console.ReadLine());
        switch (ans)
        {
            case 'y':
            case 'Y':
                strGarage = "Yes";
                break;

            case 'n':
            case 'N':
                strGarage = "No";
                break;

            default:
                strGarage = "Not Specified";
                break;
        }

        Console.WriteLine("\nDesired House Type: {0}", type);
        Console.WriteLine("Has indoor garage?  {0}", strGarage);
    }
}

This would produce:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Does the house have an indoor garage (y/n)? Y

Desired House Type: Condominium
Has indoor garage?  Yes
Press any key to continue . . .

Using Enumerations

One of the most fundamental uses of enumerations is to process them in a switch statement. To do this, you pass the value of an enumeration to a switch. The values of the enumerations are then processed in the case statements. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    Townhouse,
    Condominium
}

class Program
{
    static void Main()
    {
        string strHouseType;
        int choice;
        string strGarage = "";

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1. Single Family");
        Console.WriteLine("2. Townhouse");
        Console.WriteLine("3. Condominium");
        Console.Write("You Choice? ");
        choice = int.Parse(Console.ReadLine());

        switch((HouseType)choice)
        {
            case HouseType.SingleFamily:
                strHouseType = "Single Family";
                break;

            case HouseType.Townhouse:
                strHouseType = "Townhouse";
                break;

            case HouseType.Condominium:
                strHouseType = "Condominium";
                break;

            default:
                strHouseType = "Unknown";
                break;
        }

        Console.Write("Does the house have an indoor garage (y/n)? ");
        char ans = char.Parse(Console.ReadLine());
        switch (ans)
        {
            case 'y':
            case 'Y':
                strGarage = "Yes";
                break;

            case 'n':
            case 'N':
                strGarage = "No";
                break;

            default:
                strGarage = "Not Specified";
                break;
        }

        Console.WriteLine("\nDesired House Type: {0}", strHouseType);
        Console.WriteLine("Has indoor garage?  {0}", strGarage);
    }
}

Here is an example of running the program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Does the house have an indoor garage (y/n)? N

Desired House Type: Single Family
Has indoor garage?  No
Press any key to continue . . .
 

Previous Copyright © 2006 FunctionX, Inc. Next