Case Switches

Introduction

To let you create a conditional statement that considers various outcomes, the C# language provides a keyword named switch. It is used to create a statement that different values of the same type one after another. The primary formulat to follow is:

switch(expression)
{
	case choice1:
		statement1;
	     break;
	case choice2:
		statement2;
	     break;
	case choice-n:
		statement-n;
	     break;
}

Put the value or expression to evaluate in the parentheses of switch, This is followed by a body delimited by an opening and a closing curly bracket. In the curly bracket, create a section for each possible value passed to switch. Each sections starts with the case keyword followed by a possible and a colon. The section must end with the break keyword and a semicolon.

Between the colon and the break; expression, create a clause that would execute if the value of the case is valid.

Practical LearningPractical Learning: Introducing Conditional Switches

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New -> Project...
  3. In the middle list, click Empty Project
  4. Change the Name to Chemistry04 and press Enter
  5. To create a new file, on the main menu, click Project -> Add Class...
  6. In the middle list, mahe sure Class is selected.
    Change the Name of the file to Element
  7. Click Add
  8. Complete the Customer.cs file as follows:
    namespace Chemistry04
    {
        public class Element
        {
            public string Symbol;
            public string ElementName;
            public int    AtomicNumber;
            public double AtomicWeight;
    
            public Element(int number)
            {
                AtomicNumber = number;
            }
    
            public Element(string symbol)
            {
                Symbol = symbol;
            }
    
            public Element(int number, string symbol, string name, double mass)
            {
                Symbol = symbol;
                ElementName = name;
                AtomicWeight = mass;
                AtomicNumber = number;
            }
        }
    }

A Default Switch

When establishing the possible outcomes that a switch statement should consider, at times there will be possibilities other than those listed and you will likely want to consider them. The group of statements that don't fit any of the valid cases can be handled by a section created uwing 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;
}

By tradition, the default case is usually created the last; but that's only a suggestion. The default case can appear as the first or between any two cases.

Categories of Switching Values

Switching to a Boolean Value

The switch is used to consider various types of values.

When creating a switch statement, you can make it consider Boolean values. To do this, pass a Boolean value or variable to switch(). For one case, use a true value. For the other case, you can use a false value. Here is an example:

using static System.Console;

public class VaccinationCampaign
{
    public static int Main()
    {
        bool pregnancy = false;

        Write("Is the patient pregnant (type True or False)? ");
        pregnancy = bool.Parse( ReadLine());

        Clear();

        switch (pregnancy)
        {
            case true:
                WriteLine("Department of Health");
                WriteLine("--------------------------------------------------");
                WriteLine("For a pregnant patient, the following vaccinations are recommended:");
                WriteLine("1. Influenza (Inactivated)");
                WriteLine("2. Tdap");
                WriteLine("3. Hepatitis B: The patient should consult her physician");
                break;
            case false:
                WriteLine("The patient will not need pregnacy recommendations");
                break;
        }
        
        WriteLine("==================================================");

        return 0;
    }
}

Here is an example of running the program:

Is the patient pregnant (type True or False)? True

The second part would be:

Department of Health
--------------------------------------------------
For a pregnant patient, the following vaccinations are recommended:
1. Influenza (Inactivated)
2. Tdap
3. Hepatitis B: The patient should consult her physician
==================================================
Press any key to continue . . .

A Boolean value is considered as being True or else. As a result, you can one true case and the other would be a default clause. Here is an example:

using static System.Console;

public class VaccinationCampaign
{
    public static int Main()
    {
        bool pregnancy = false;

        Write("Is the patient pregnant (type True or False)? ");
        pregnancy = bool.Parse( ReadLine());

        Clear();

        switch (pregnancy)
        {
            case true:
                WriteLine("Department of Health");
                WriteLine("--------------------------------------------------");
                WriteLine("For a pregnant patient, the following vaccinations are recommended:");
                WriteLine("1. Influenza (Inactivated)");
                WriteLine("2. Tdap");
                WriteLine("3. Hepatitis B: The patient should consult her physician");
                break;
            default:
                WriteLine("The patient will not need a pregnacy text");
                break;
        }
        WriteLine("==================================================");

        return 0;
    }
}

Switching to Integral Values

A switch can consider integral values. In this case, you can pass eother a constant value or an integer-based variable to it. Then in each case, process each of the outcomes.

Practical LearningPractical Learning: Introducing Integral Switches

  1. To create a new file, in the Solution Explorer, right-click Chemistry04 -> Add -> Class...
  2. In the middle list, make sure Class is selected.
    Change the Name to Chemistry
  3. Press Enter
  4. Complete the document as follows:
    using static System.Console;
    
    namespace Chemistry04
    {
        public class Chemistry
        {
            private static void Describe(Element e)
            {
                WriteLine("Chemistry - " + e.ElementName);
                WriteLine("------------------------");
                WriteLine("Symbol:        " + e.Symbol);
                WriteLine("Element Name:  " + e.ElementName);
                WriteLine("Atomic Number: " + e.AtomicNumber);
                WriteLine("Atomic Weight: " + e.AtomicWeight);
            }
    
            public static int Main()
            {
                Element elm = null;
    
                Element h = new Element(1, "H", "Hydrogen", 1.008);
                Element he = new Element(2, "He", "Helium", 4.002602);
                Element li = new Element(3, "Li", "Lithium", 6.94);
                Element be = new Element(4, "Be", "Beryllium", 9.0121831);
                Element b = new Element(5, "B", "Boron", 10.81);
                Element c = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
                Element n = new Element(number: 7, symbol: "N", name: "Nitrogen", mass: 14.007);
                Element o = new Element(number: 8, symbol: "O", name: "Oxygen", mass: 15.999);
                Element f = new Element(number: 9, symbol: "F", name: "Fluorine", mass: 15.999);
                Element ne = new Element(number: 10, symbol: "Ne", name: "Neon", mass: 20.1797);
                Element na = new Element(11, "Na", "Sodium", mass: 22.98976928);
                Element mg = new Element(12, "Mg", "Magnesium", 24.305);
                Element al = new Element(13, "Al", "Aluminium", 26.9815385);
    
                WriteLine("Chemistry - Period Table");
                WriteLine("------------------------------------------------");
                Write("Type the atomic number of an element you want to review (1-15): ");
                int answer = int.Parse(ReadLine());
    
                Clear();
    
                switch(answer)
                {
                    case 1:
                        elm = h;
                        break;
                    case 2:
                        elm = he;
                        break;
                    case 3:
                        elm = li;
                        break;
                    case 4:
                        elm = be;
                        break;
                    case 5:
                        elm = b;
                        break;
                    case 6:
                        elm = c;
                        break;
                    case 7:
                        elm = n;
                        break;
                    case 8:
                        elm = o;
                        break;
                    case 9:
                        elm = f;
                        break;
                    case 10:
                        elm = ne;
                        break;
                    case 11:
                        elm = na;
                        break;
                    case 12:
                        elm = mg;
                        break;
                    case 13:
                        elm = al;
                        break;
                    default:
                        WriteLine("You must select a number between 1 (included) and 13 (included)");
                        break;
                }
    
                Describe(elm);
                WriteLine("================================================");
    
                return 0;
            }
        }
    }
  5. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry - Period Table
    ------------------------------------------------
    Type the atomic number of an element you want to review (1-13):
  6. When prompted, type 13
  7. Press Enter:
    Chemistry - Aluminium
    ------------------------
    Symbol:        Al
    Element Name:  Aluminium
    Atomic Number: 13
    Atomic Weight: 26.9815385
    ================================================
    Press any key to continue . . .
  8. Press Enter tp close the window and return to your programming environment

Switching Strings

A switch statement can be used to evaluate string values. To proceed, pass a double-quoted symbol or character, a string, or a variable that holds a string. For each case, process one of the values that can be considered.

Practical LearningPractical Learning: Switching Strings

  1. Change the code in the Chemistry class as follows:
    using static System.Console;
    
    namespace Chemistry04
    {
        public class Chemistry
        {
            private static void Describe(Element e)
            {
                WriteLine("Chemistry - " + e.ElementName);
                WriteLine("------------------------");
                WriteLine("Symbol:        " + e.Symbol);
                WriteLine("Element Name:  " + e.ElementName);
                WriteLine("Atomic Number: " + e.AtomicNumber);
                WriteLine("Atomic Weight: " + e.AtomicWeight);
            }
    
            public static int Main()
            {
                Element elm = null;
    
                Element h = new Element(1, "H", "Hydrogen", 1.008);
                Element he = new Element(2, "He", "Helium", 4.002602);
                Element li = new Element(3, "Li", "Lithium", 6.94);
                Element be = new Element(4, "Be", "Beryllium", 9.0121831);
                Element b = new Element(5, "B", "Boron", 10.81);
                Element c = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
                Element n = new Element(number: 7, symbol: "N", name: "Nitrogen", mass: 14.007);
                Element o = new Element(number: 8, symbol: "O", name: "Oxygen", mass: 15.999);
                Element f = new Element(number: 9, symbol: "F", name: "Fluorine", mass: 15.999);
                Element ne = new Element(number: 10, symbol: "Ne", name: "Neon", mass: 20.1797);
                Element na = new Element(11, "Na", "Sodium", mass: 22.98976928);
                Element mg = new Element(12, "Mg", "Magnesium", 24.305);
                Element al = new Element(13, "Al", "Aluminium", 26.9815385);
                Element si = new Element() { ElementName = "Silicon", AtomicWeight = 28.085, Symbol = "Si", AtomicNumber = 14 };
                Element p = new Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998, Symbol = "P", AtomicNumber = 15 };
                Element s = new Element(16, "S", "Sulfur", 32.06);
    
    
                WriteLine("Chemistry - Periodic Table");
                WriteLine("------------------------------------------------");
                Write("Type the chemical symbol of an element you want to review (from H to S): ");
                string answer = ReadLine();
    
                Clear();
    
                switch (answer)
                {
                    default:
                        WriteLine("You must type H, He, Li, Be, B, C, N, O, F, Ne, Na Mg, Al, Si, P, or S.");
                        break;
                    case "H":
                        elm = h;
                        break;
                    case "He":
                        elm = he;
                        break;
                    case "Li":
                        elm = li;
                        break;
                    case "Be":
                        elm = be;
                        break;
                    case "B":
                        elm = b;
                        break;
                    case "C":
                        elm = c;
                        break;
                    case "N":
                        elm = n;
                        break;
                    case "O":
                        elm = o;
                        break;
                    case "F":
                        elm = f;
                        break;
                    case "Ne":
                        elm = ne;
                        break;
                    case "Na":
                        elm = na;
                        break;
                    case "Mg":
                        elm = mg;
                        break;
                    case "Al":
                        elm = al;
                        break;
                    case "Si":
                        elm = si;
                        break;
                    case "P":
                        elm = p;
                        break;
                    case "S":
                        elm = s;
                        break;
                }
    
                Describe(elm);
                WriteLine("================================================");
    
                return 0;
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry - Periodic Table
    ------------------------------------------------
    Type the chemical symbol of an element you want to review (from H to S):
  3. When prompted, type Si
  4. Press Enter:
    Chemistry - Silicon
    ------------------------
    Symbol:        Si
    Element Name:  Silicon
    Atomic Number: 14
    Atomic Weight: 28.085
    ================================================
    Press any key to continue . . .
  5. Press Enter tp close the window and return to your programming environment

Switching an Enumeration

The value that a switch condition processes can be the members of an enumeration. Start by passing a variable declared from an enumeration or an expresison that produces a value from the enumeration. For each case, use one of the members of the enumeration. Here is an example:

using static System.Console;

namespace HotelManagement
{
    public class Exercise
    {
        public enum AvailabilityStatus
        {
            Available,
            Occupied,
            Reserved,
            NeedsService
        }

        static int Main()
        {
            WriteLine("Hotel Management");
            int roomNumber = 204;
            AvailabilityStatus status = AvailabilityStatus.Available;

            WriteLine("Room #: " + roomNumber);
            
            switch (status)
            {
                case AvailabilityStatus.Available:
                    WriteLine("The room is currently available.");
                    break;
                case AvailabilityStatus.Occupied:
                    WriteLine("The room is currently rented to a customer.");
                    break;
                case AvailabilityStatus.Reserved:
                    WriteLine("The room has been reserved to a customer.");
                    break;
                case AvailabilityStatus.NeedsService:
                    WriteLine("The room needs service, such as maintenance, or something else.");
                    break;
            }

            return 0;
        }
    }
}

This would produce:

Hotel Management
Room #: 204
The room is currently available.
Press any key to continue . . .

Options on Using Conditional Switches

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 a semi-colon. Type another case using the same formula. When the cases have been listed, create the necessary statement(s) and end with a break line. Here is an example:

using static System.Console;

public class VaccinationCampaign
{
    public static int Main()
    {
        int ageRange = 0;
        string gender = "u";
        string pregnancy = null;
        string patientName = null;

        WriteLine("Department of Health");
        WriteLine("-------------------------------------------------------");
        WriteLine("Patient's Diagnosis");
        Write("Patient's Name: ");
        patientName = ReadLine();
        Write("Patient's Gender (m - Male, f - Female): ");
        gender = ReadLine();
        WriteLine("Patients Age Ranges");
        WriteLine("1 - Toddler");
        WriteLine("2 - Kid");
        WriteLine("3 - Teen");
        WriteLine("4 - Adult");
        Write("Type the patient's age range: ");
        ageRange = int.Parse(ReadLine());

        switch (ageRange)
        {
            case 1:
                WriteLine("The government recommends that you follow the immunication schedule for the first 15 months.");
                break;
            case 2:
                WriteLine("Consult the child's pediatrician and the school system for the list of recommended as well as required vaccines.");
                break;
            case 3:
            case 4:
                Write("Is the patient pregnant (y/n)? ");
                pregnancy = ReadLine();
                break;
        }
            
        Clear();

        WriteLine("Department of Health");
        WriteLine("-------------------------------------------------------");
        WriteLine("Patient's Diagnosis");
        WriteLine("Name:   " + patientName);
        switch (gender)
        {
            case "m":
            case "M":
                WriteLine("Gender: Male");
                break;
            default:
                WriteLine("Gender: Unknown");
                break;
            case "f":
            case "F":
                WriteLine("Gender: Female");
                break;
        }

        WriteLine("Age Range: " + ageRange);

        switch(pregnancy)
        {
            case "y":
            case "Y":
                WriteLine("The following vaccinations are recommended:");
                WriteLine("1. Influenza (Inactivated)");
                WriteLine("2. Tdap");
                WriteLine("3. Hepatitis B: The patient should consult her physician");
                break;
        }

        WriteLine("=======================================================");

        return 0;
    }
}

Here is an example of running the program:

Department of Health
-------------------------------------------------------
Patient's Diagnosis
Patient's Name: Yolanda Mishra
Patient's Gender (m - Male, f - Female): F
Patients Age Ranges
1 - Toddler
2 - Kid
3 - Teen
4 - Adult
Type the patient's age range: 2

The second part would produce:

Department of Health
-------------------------------------------------------
Patient's Diagnosis
Name:   Yolanda Mishra
Gender: Female
Age Range: 2
=======================================================
Press any key to continue . . .

Here is another test of the program:

Department of Health
-------------------------------------------------------
Patient's Diagnosis
Patient's Name: Jennifer Humbleton
Patient's Gender (m - Male, f - Female): f
Patients Age Ranges
1 - Toddler
2 - Kid
3 - Teen
4 - Adult
Type the patient's age range: 3
Is the patient pregnant (y/n)? Y

The second part would produce:

Department of Health
-------------------------------------------------------
Patient's Diagnosis
Name:   Jennifer Humbleton
Gender: Female
Age Range: 3
The following vaccinations are recommended:
1. Influenza (Inactivated)
2. Tdap
3. Hepatitis B: The patient should consult her physician
=======================================================
Press any key to continue . . .

In the above example, we used only two cases as a combination. You can combine as many cases as necessary.

Practical LearningPractical Learning: Combining Switches

  1. Change the Chemisty class follows:
    using static System.Console;
    
    namespace Chemistry04
    {
        public class Chemistry
        {
            private static void Describe(Element e)
            {
                WriteLine("Chemistry - " + e.ElementName);
                WriteLine("------------------------");
                WriteLine("Symbol:        " + e.Symbol);
                WriteLine("Element Name:  " + e.ElementName);
                WriteLine("Atomic Number: " + e.AtomicNumber);
                WriteLine("Atomic Weight: " + e.AtomicWeight);
            }
    
            public static int Main()
            {
                Element elm = null;
    
                Element h = new Element(1, "H", "Hydrogen", 1.008);
                Element he = new Element(2, "He", "Helium", 4.002602);
                Element li = new Element(3, "Li", "Lithium", 6.94);
                Element be = new Element(4, "Be", "Beryllium", 9.0121831);
                Element b = new Element(5, "B", "Boron", 10.81);
                Element c = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6);
                Element n = new Element(number: 7, symbol: "N", name: "Nitrogen", mass: 14.007);
                Element o = new Element(number: 8, symbol: "O", name: "Oxygen", mass: 15.999);
                Element f = new Element(number: 9, symbol: "F", name: "Fluorine", mass: 15.999);
                Element ne = new Element(number: 10, symbol: "Ne", name: "Neon", mass: 20.1797);
                Element na = new Element(11, "Na", "Sodium", mass: 22.98976928);
                Element mg = new Element(12, "Mg", "Magnesium", 24.305);
                Element al = new Element(13, "Al", "Aluminium", 26.9815385);
                Element si = new Element() { ElementName = "Silicon", AtomicWeight = 28.085, Symbol = "Si", AtomicNumber = 14 };
                Element p = new Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998, Symbol = "P", AtomicNumber = 15 };
                Element s = new Element(16, "S", "Sulfur", 32.06);
                Element cl = new Element() { ElementName = "Chlorine", AtomicWeight = 35.446, Symbol = "Cl", AtomicNumber = 17 };
    
    
                WriteLine("Chemistry - Periodic Table");
                WriteLine("------------------------------------------------");
                Write("Type the chemical symbol of an element you want to review (from H to Cl): ");
                string answer = ReadLine();
    
                Clear();
    
                switch (answer)
                {
                    default:
                        WriteLine("You must type H, He, Li, Be, B, C, N, O, F, Ne, Na Mg, Al, Si, P, S, or Cl.");
                        break;
                    case "cl":
                    case "Cl":
                    case "cL":
                    case "CL":
                        elm = cl;
                        break;
                    case "h":
                    case "H":
                        elm = h;
                        break;
                    case "he":
                    case "HE":
                    case "He":
                    case "hE":
                        elm = he;
                        break;
                    case "li":
                    case "Li":
                    case "LI":
                    case "lI":
                        elm = li;
                        break;
                    case "be":
                    case "Be":
                    case "bE":
                    case "BE":
                        elm = be;
                        break;
                    case "b":
                    case "B":
                        elm = b;
                        break;
                    case "C":
                    case "c":
                        elm = c;
                        break;
                    case "N":
                    case "n":
                        elm = n;
                        break;
                    case "o":
                    case "O":
                        elm = o;
                        break;
                    case "F":
                    case "f":
                        elm = f;
                        break;
                    case "NE":
                    case "ne":
                    case "Ne":
                    case "nE":
                        elm = ne;
                        break;
                    case "Na":
                    case "na":
                    case "NA":
                    case "nA":
                        elm = na;
                        break;
                    case "MG":
                    case "mG":
                    case "Mg":
                    case "mg":
                        elm = mg;
                        break;
                    case "Al":
                    case "AL":
                    case "aL":
                    case "al":
                        elm = al;
                        break;
                    case "SI":
                    case "Si":
                    case "sI":
                    case "si":
                        elm = si;
                        break;
                    case "p":
                    case "P":
                        elm = p;
                        break;
                    case "S":
                    case "s":
                        elm = s;
                        break;
                }
    
                Describe(elm);
                WriteLine("================================================");
    
                return 0;
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry - Periodic Table
    ------------------------------------------------
    Type the chemical symbol of an element you want to review (from H to Cl):
  3. When prompted, type CL
  4. Press Enter:
    Chemistry - Chlorine
    ------------------------
    Symbol:        Cl
    Element Name:  Chlorine
    Atomic Number: 17
    Atomic Weight: 35.446
    ================================================
    Press any key to continue . . .
  5. Press Enter to close the window and return to your programming environment

Nesting and Switches

When you have created a conditional statement (if, if...else, and their variants), you can create a switch statement in the body of such a condition. This is referred to as nesting the statement.

In body of a case of a switch statement, you can create one or more conditional statements. This also is referred to as nesting.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next