Case Switches

Introduction

Imagine you have a list of values that can each respond to a condition as being true but you want to consider only one of those values. To let you check each one of those values, the C# language provides the switch conditional statement. It takes a value as done when calling a method. It also has a body delimited by curly brackets. In its body, each value is preceded by the case keyword. The formula to create a switch statement is:

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

The object or expression that holds the value to examine is passed to the parentheses of switch. The body of the switch contains one or more sections that each starts with the case keyword. Each case section considers one possible value that is followed by a colon. After the case statement, write code that must be applied to only that outcome. The case clause must end with break;.

The switch statement accepts different types of expressions or values.

Practical LearningPractical Learning: Switching a String

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the central list, click ASP.NET Web Application (.NET Framework) and change the project Name to PayrollPreparation07
  4. Click OK
  5. In the New ASP.NET Web Application, make sure Empty is selected and click OK
  6. In the Solution Explorer, right-click PayrollPreparation07 -> Add -> New Item...
  7. In the left list, expand Web and click Razor
  8. In the middle list, click Web Page (Razor v3)
  9. Set the name as Index
  10. Press Enter

Switching a String

Probably the easiest type of value to deal with is text because it can hold any value. This means that the expression you want to consider could have disparate combinations of characters. Still in the body of the switch, each case section should deal with a valid value of the possible outcomes.

Practical LearningPractical Learning: Switching a String

  1. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>State Income Tax - Flat-Rate States</title>
    <style>
    .container {
        margin: auto;
        width: 320px;
    }
    </style>
    </head>
    <body>
        <div class="container">
            @{
                string state = "";
                double salary = 0.00;
                string strTaxes = "0.00";
                string strNetPay = "0.00";
                string residence = "";
    
                if (IsPost)
                {
                    double taxes = 0.00;
                    state = Request["cbxStates"];
                    salary = Convert.ToDouble(Request["txtGrossSalary"]);
    
                    switch (state)
                    {
                        case "Colorado":
                            taxes = salary * 4.63 / 100.00;
                            residence = "Colorado (4.63%)";
                            break;
                        case "Illinois":
                            taxes = salary * 3.75 / 100.00;
                            residence = "Illinois (3.75%)";
                            break;
                        case "Indiana":
                            taxes = salary * 3.3 / 100.00;
                            residence = "Indiana (3.3%)";
                            break;
                        case "Michigan":
                            taxes = salary * 4.25 / 100.00;
                            residence = "Michigan (4.25%)";
                            break;
                        case "North Carolina":
                            taxes = salary * 5.75 / 100.00;
                            residence = "North Carolina (5.75%)";
                            break;
                        case "Pennsylvania":
                            taxes = salary * 3.07 / 100.00;
                            residence = "Pennsylvania (3.07%)";
                            break;
                        case "Utah":
                            taxes = salary * 5 / 100.00;
                            residence = "Utah (5%)";
                            break;
                    }
    
                    strTaxes = taxes.ToString("F");
                    strNetPay = (salary - taxes).ToString("F");
                }
            }
    
            <h3 style="text-align: center">State Income Tax</h3>
            <h4 style="text-align: center">Flat-Rate States</h4>
    
            <form name="frmIncomeTax" method="post">
                <table>
                    <tr>
                        <td style="width: 150px">Gross Salary:</td>
                        <td><input type="text" name="txtGrossSalary" value="@salary" /></td>
                    </tr>
                    <tr>
                        <td>State:</td>
                        <td>
                            <select name="cbxStates">
                                <option value="Nothing"></option>
                                <option value="Colorado">Colorado</option>
                                <option value="Illinois">Illinois</option>
                                <option value="Indiana">Indiana</option>
                                <option value="Michigan">Michigan</option>
                                <option value="North Carolina">North Carolina</option>
                                <option value="Pennsylvania">Pennsylvania</option>
                                <option value="Utah">Utah</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
    
                        <td style="text-align: center"><input type="submit" name="btnCalculate" value="Calculate" /></td>
                    </tr>
                    <tr>
                        <td>Employee Residence:</td>
                        <td><input type="text" name="txtEmployeeResidence" value="@residence" /></td>
                    </tr>
                    <tr>
                        <td>State Income Tax:</td>
                        <td><input type="text" name="txtIncomeTax" value="@strTaxes" /></td>
                    </tr>
                    <tr>
                        <td>Net Pay:</td>
                        <td><input type="text" name="txtNetPay" value="@strNetPay" /></td>
                    </tr>
                </table>
            </form>
        </div>
    </body>
    </html>
  2. To execute the application, on the main menu,, click Debug -> Start Without Debugging

    Introducing Switch Statements

  3. In the Gross Salary text box, type a number such as 2814.83
  4. Select a state in the combo box:

    Introducing Switch Statements

    Introducing Switch Statements

  5. Click the Calculate button:

    Introducing Switch Statements

  6. Close the browser and return to your programming environment

Switching to a Boolean Value

If you want to consider one of two outcomes of a Boolean expression, pass a Boolean variable or an expression that produces a Boolean value to a switch statement. One case would consider a true value and another case would consider a false value.

Switching an Integer

Probably the most regularly used type of value in a switch expression is a natural number. The object or expression passed to the switch can come from any source as long as it represents a constant integer.

Practical LearningPractical Learning: Introducing Logical Disjunctions

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click ASP.NET Web Application (.NET Framework) and set the project Name to Chemistry08
  3. Click OK
  4. In the New ASP.NET Web Application, make sure Empty is selected and click OK
  5. In the Solution Explorer, right-click Chemistry08 -> Add -> Add ASP.NET Folder -> App_Code
  6. In the Solution Explorer, right-click App_Code -> Add -> Class...
  7. Replace the name with Element
  8. Click Add
  9. Change the code as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Chemistry08.App_Code
    {
        public enum Phase
        {
            Gas,
            Liquid,
            Solid,
            Unknown
        }
    
        public class Element
        {
            public string Symbol { get; set; } = "H";
            public string ElementName { get; set; } = "Hydrogen";
            public int AtomicNumber { get; set; } = 1;
            public decimal AtomicWeight { get; set; } = 1.008M;
            public Phase Phase { get; set; } = Phase.Gas;
    
            public Element()
            {
            }
    
            public Element(int number)
            {
                AtomicNumber = number;
            }
    
            public Element(string symbol)
            {
                Symbol = symbol;
            }
    
            public Element(int number, string symbol, string name, decimal mass)
            {
                Symbol = symbol;
                ElementName = name;
                AtomicWeight = mass;
                AtomicNumber = number;
            }
        }
    }
  10. In the Solution Explorer, right-click Chemistry08 -> Add -> New Folder
  11. Type Content and press Enter
  12. In the Solution Explorer, right-click Content -> Add -> New Item...
  13. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click Style Sheet
  14. Replace the name with Site
  15. Click Add
  16. Change the code as follows:
    body {
        margin: 0;
        background-color: #FFFFFF;
    }
    
    #top-banner {
        top: 0;
        width: 100%;
        height: 60px;
        position: fixed;
        background-color: #003366;
        border-bottom: 5px solid black;
    }
    
    .title-holder {
        top: 65px;
        width: 100%;
        height: 34px;
        position: fixed;
    }
    
    .container {
        width: 300px;
        margin: auto;
        padding-top: 10px;
    }
    
    .item-selection {
        width: 350px;
        margin: auto;
        padding-top: 120px;
    }
    
    #main-title {
        font-weight: 800;
        margin-top: 16px;
        font-size: 2.12em;
        text-align: center;
        color: yellow;
        font-family: Garamond, 'Times New Roman', Georgia, serif
    }
    
    #sub-title {
        color: navy;
        font-weight: 600;
        padding-top: 2px;
        font-size: 1.68em;
        text-align: center;
        font-family: Garamond, 'Times New Roman', Georgia, serif
    }
    
    .small-text { width:       40px;  }
    .emphasize  { font-weight: bold;  }
    .left-col   { width:       120px; }
  17. In the Solution Explorer, right-click Chemistry08 -> Add -> New Item...
  18. In the left list, expand Web and click Razor
  19. In the middle list, click Web Page (Razor v3)
  20. Change the name to Index
  21. Click Add
  22. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Chemistry</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    @helper SelectElement(int number)
    {
        Chemistry08.App_Code.Element selected = new Chemistry08.App_Code.Element();
    
        Chemistry08.App_Code.Element H = new Chemistry08.App_Code.Element(1, "H", "Hydrogen", 1.008M) { Phase = Chemistry08.App_Code.Phase.Gas };
        Chemistry08.App_Code.Element He = new Chemistry08.App_Code.Element(2, "He", "Helium", 4.002602M) { Phase = Chemistry08.App_Code.Phase.Gas };
        Chemistry08.App_Code.Element Li = new Chemistry08.App_Code.Element(3, "Li", "Lithium", 6.94M) { Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element Be = new Chemistry08.App_Code.Element(4, "Be", "Beryllium", 9.0121831M) { Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element B = new Chemistry08.App_Code.Element(5, "B", "Boron", 10.81M) { Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element C = new Chemistry08.App_Code.Element(number: 6, symbol: "C", name: "Carbon", mass: 12.011M) { Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element N = new Chemistry08.App_Code.Element(7);
        N.Symbol = "N";
        N.AtomicWeight = 14.007M;
        N.ElementName = "Nitrogen";
        N.Phase = Chemistry08.App_Code.Phase.Gas;
    
        Chemistry08.App_Code.Element O = new Chemistry08.App_Code.Element("O")
        {
            AtomicNumber = 8,
            ElementName = "Oxygen",
            AtomicWeight = 15.999M,
            Phase = Chemistry08.App_Code.Phase.Gas
        };
        Chemistry08.App_Code.Element F = new Chemistry08.App_Code.Element("F")
        {
            AtomicNumber = 9,
            ElementName = "Fluorine",
            AtomicWeight = 15.999M,
            Phase = Chemistry08.App_Code.Phase.Gas
        };
        Chemistry08.App_Code.Element Ne = new Chemistry08.App_Code.Element("Ne")
        {
            AtomicNumber = 10,
            ElementName = "Neon",
            AtomicWeight = 20.1797M,
            Phase = Chemistry08.App_Code.Phase.Gas
        };
        Chemistry08.App_Code.Element Na = new Chemistry08.App_Code.Element(11, "Na", "Sodium", 22.98976928M) { Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element Mg = new Chemistry08.App_Code.Element(12, "Mg", "Magnesium", 24.305M) { Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element Al = new Chemistry08.App_Code.Element(13, "Al", "Aluminium", 26.9815385M) { Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element Si = new Chemistry08.App_Code.Element() { ElementName = "Silicon", AtomicWeight = 28.085M, Symbol = "Si", AtomicNumber = 14, Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element P = new Chemistry08.App_Code.Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998M, Symbol = "P", AtomicNumber = 15, Phase = Chemistry08.App_Code.Phase.Solid };
        Chemistry08.App_Code.Element S = new Chemistry08.App_Code.Element(16, "S", "Sulfur", 32.06M) { Phase = Chemistry08.App_Code.Phase.Solid };
    
        switch (number)
        {
            case 1:
                selected = H;
                break;
            case 2:
                selected = He;
                break;
            case 3:
                selected = Li;
                break;
            case 4:
                selected = Be;
                break;
            case 5:
                selected = B;
                break;
            case 6:
                selected = C;
                break;
            case 7:
                selected = N;
                break;
            case 8:
                selected = O;
                break;
            case 9:
                selected = F;
                break;
            case 10:
                selected = Ne;
                break;
            case 11:
                selected = Na;
                break;
            case 12:
                selected = Mg;
                break;
            case 13:
                selected = Al;
                break;
            case 14:
                selected = Si;
                break;
            case 15:
                selected = P;
                break;
            case 16:
                selected = S;
                break;
        }
    
    <form name="frmChemistry" method="post">
        <table>
            <tr>
                <td class="left-col emphasize">Atomic Number:</td>
                    <td><input type="text" name="txtAtomicNumber" value=@selected.AtomicNumber /></td>
                </tr>
                <tr>
                    <td class="emphasize">Symbol:</td>
                    <td><input type="text" name="txtSymbol" value=@selected.Symbol /></td>
                </tr>
                <tr>
                    <td class="emphasize">Element Name:</td>
                    <td><input type="text" name="txtElementName" value=@selected.ElementName /></td>
                </tr>
                <tr>
                    <td class="emphasize">Atomic Weight:</td>
                    <td><input type="text" name="txtAtomicWeight" value=@selected.AtomicWeight /></td>
                </tr>
                <tr>
                    <td class="emphasize">Phase:</td>
                    <td><input type="text" name="txtAtomicWeight" value=@selected.Phase /></td>
                </tr>
            </table>
        </form>
    }
    
    @{
        int valueEntered = 0;
    
        if (IsPost)
        {
            valueEntered = Request["txtValueEntered"].AsInt();
        }
    }
    
    <div id="top-banner">
        <p id="main-title">Chemistry</p>
    </div>
    
    <div class="title-holder">
        <div id="sub-title"></div>
        <hr />
    </div>
    
    <div class="item-selection">
        <form name="frmChemistry" method="post">
            <table>
                <tr>
                    <td class="emphasize left-col">Enter Atomic #:</td>
                    <td>
                        <input type="text" name="txtValueEntered" class="small-text" value="@valueEntered" />
                        <input type="submit" name="btnFind" value="Find" style="width: 70px;" />
                    </td>
                </tr>
            </table>
        </form>
    
        @SelectElement(@valueEntered)
    </div>
    </body>
    </html>
    
  23. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Multiple Conditions

  24. In the top text box, type a number between 1 (included) and 16
  25. Click the Find button:

    Introduction to Boolean Disjunctions

  26. Close the browser and return to your programming environment

Switching an Enumeration

The switch operation supports values based on an enumeration. When creating the statement, you can pass an expression that holds the value of an enumeration. In the body of the switch clause, each case can represent one of the members of the enumeration.

Practical LearningPractical Learning: Introducing if...else if Conditions

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click ASP Applicationct (.NET Framework) and set the project Name to CompoundInterest3
  3. In the New ASP.NET Web Application dialog box, make sure Empty is selected and click OK
  4. In the Solution Explorer, right-click the name of the project -> Add -> New Item...
  5. In the left frame, click Code
  6. In the middle list, click Code File
  7. Change the file Name to Frequency
  8. Click Add
  9. IIn the empty document, type the following code:
    public enum CompoundFrequency
    {
        Daily        = 1,
        Weekly       = 2,
        Monthly      = 3,
        Quaterly     = 4,
        Semiannually = 5,
        Annually     = 6
    }
  10. On the main menu, click Project -> Add New Item...
  11. In the left frame, expand Web and click Razor
  12. Change the name to Index
  13. Click Add
  14. Type code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Compound Interest</title>
    <style>
    .container {
        margin: auto;
        width: 550px;
    }
    </style>
    </head>
    <body>
    @{
        CompoundFrequency compounding = CompoundFrequency.Monthly;
    
        double periods = 0;
        double principal = 0.00;
        double interestRate = 0.00;
        string strFutureValue = "0.00";
        string strInterestEarned = "0.00";
    
        if (IsPost)
        {
            double frequency = 0.00;
            principal = Convert.ToDouble(Request["txtPrincipal"]);
            interestRate = Convert.ToDouble(Request["txtInterestRate"]);
            periods = Convert.ToDouble(Request["txtPeriods"]);
    
            double iRate = interestRate / 100.00;
            compounding = (CompoundFrequency)Request["rdoCompoundFrequency"].AsInt();
    
            switch (compounding)
            {
                case CompoundFrequency.Daily:
                    frequency = 365.00;
                    break;
    
                case CompoundFrequency.Weekly:
                    frequency = 52.00;
                    break;
    
                case CompoundFrequency.Monthly:
                    frequency = 12.00;
                    break;
    
                case CompoundFrequency.Quaterly:
                    frequency = 4.00;
                    break;
    
                case CompoundFrequency.Semiannually:
                    frequency = 2.00;
                    break;
    
                case CompoundFrequency.Annually:
                    frequency = 1.00;
                    break;
            }
    
            double futureValue = principal * Math.Pow((1.00 + (iRate / frequency)), frequency * periods);
            double interestEarned = futureValue - principal;
    
            strInterestEarned = interestEarned.ToString("F");
            strFutureValue = futureValue.ToString("F");
    
        }
    }
    
    <div class="container">
        <h2 style="text-align: center">Compound Interest</h2>
    
        <form name="frmCompoundInterest" method="post">
                <table style="width: 550px">
                    <tr>
                        <td style="width: 120px; font-weight: bold">Principal:</td>
                        <td><input type="text" name="txtPrincipal" style="width: 80px" value="@principal" /></td>
                        <td rowspan="3" style="font-weight: bold">
                            Compound Frequency
                            <table>
                                <tr>
                                    <td>Daily</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="1" /></td>
                                    <td style="width: 30px">&nbsp;</td>
                                    <td>Quaterly</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="4" /></td>
                                </tr>
                                <tr>
                                    <td>Weekly</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="2" /></td>
                                    <td>&nbsp;</td>
                                    <td>Semiannually</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="5" /></td>
                                </tr>
                                <tr>
                                    <td>Monthly</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="3" /></td>
                                    <td>&nbsp;</td>
                                    <td>Annually</td>
                                    <td><input type="radio" name="rdoCompoundFrequency" value="6" /></td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    <tr>
                        <td style="font-weight: bold">Interest Rate:</td>
                        <td><input type="text" name="txtInterestRate" style="width: 80px" value="@interestRate" /> %</td>
                    </tr>
                    <tr>
                        <td style="font-weight: bold">Periods:</td>
                        <td><input type="text" name="txtPeriods" style="width: 80px" value="@periods" /> Years</td>
                    </tr>
                </table>
    
                <p style="text-align: center"><input type="submit" name="btnCalculate" style="width: 400px" value="Calculate" /></p>
    
                <table style="width: 550px">
                    <tr>
                        <td style="width: 120px">Interest Earned:</td>
                        <td><input type="text" name="txtInterestEarned" style="width: 100px" value="@strInterestEarned" /></td>
                        <td>Future Value:</td>
                        <td><input type="text" name="txtFutureValue" style="width: 80px" value="@strFutureValue" /></td>
                    </tr>
                </table>
        </form>
    </div>
    </body>
    </html>
  15. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging:

    Switching an Enumeration

  16. In the Principal text box, type a number such as 3450
  17. In the Interest Rate text box, type a number such as 12.50

  18. In the Periods text box, type a natural number such as 4
  19. In the Compound Frequency group box, click one of the radio buttons such as Monthly:

    Switching an Enumeration

  20. Click the Calculate button:

    Switching an Enumeration

  21. Close the browser and return to your programming environment
  22. Close your programming environment

Previous Copyright © 2001-2019, FunctionX Next