Introduction to Case Switches

Breaking a Case

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. In the Visual Studio 2019 dialog box, click Create a New Project and click Next (if Microsoft Visual Studio was already opened, on its main menu, click File -> New -> Project...)
  3. In the list of projects templates, click Windows Forms App (.NET Framework)
  4. Click Next
  5. Change the project Name to PayrollEvaluation05
  6. Click Create
  7. In the Solution Explorer, right-click Form1.cs -> Rename
  8. Type PayrollEvaluation and press Enter
  9. Read the message box and click Yes
  10. In the Toolbox, under Common Controls, click ComboBox
  11. Click the form
  12. While the combo box is selected on the form, in the Properties window, click Items and click its button
  13. In the text box of the String Collection Editor, type each of the following strings:
    Nothing
    Utah
    Illinois
    Indiana
    Michigan
    Colorado
    Pennsylvania
    North Carolina

    String Collection Editor

  14. Click OK
  15. Complete the design of the form as follows:

    Switching a String

    Control (Name) Text TextAlign
    Label   Gross Salary:  
    TextBox txtGrossSalary 0 Right
    Label   State:
    TextBox cbxStates    
    Button btnCalculate Calculate  
    Label   txtEmployeeResidence
    TextBox txtEmployeeResidence Right
    Label   txtIncomeTax
    TextBox Right
    Label   Net Pay:
    TextBox txtNetPay Right
  16. Double-click eh Calculate button
  17. Right-click inside the Code Editor and click Remove and Sort Usings

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. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PayrollPreparation07
    {
        public partial class PayrollEvaluation : Form
        {
            public PayrollEvaluation()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double taxes = 0.00;
                string residence = "None";
                string state = cbxStates.Text;
                double salary = Convert.ToDouble(txtGrossSalary.Text);
                
                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;
                }
    
                txtEmployeeResidence.Text = residence;
                txtStateIncomeTax.Text = taxes.ToString("F"); 
                txtNetPay.Text = (salary - taxes).ToString("F");
            }
        }
    }
  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. Click the arrow of the combo box to select a state:

    Introducing Switch Statements

  5. From the list, click Indiana:

    Introducing Switch Statements

  6. Click the Calculate button:

    Introducing Switch Statements

  7. Close the form and return to your programming environment
  8. Start Microsoft Visual Studio and, on the Visual Studion 2019 dialog box, click Create a New Project (if Microsoft Visual Studio was already launched, on the main menu of, click File -> New -> Project...)
  9. In the list of projects templates, click Winows Forms App (.NET Framework)
  10. Click Next
  11. Change the project Name to PayrollEvaluation06
  12. Click Create
  13. In the Solution Explorer, right-click PayrollEvaluation06 -> Add -> Class...
  14. Change the name to Calculations
  15. Click Add
  16. Right-click inside the Code Editor -> Remove and Sort Usings
  17. Change the class as follows:
    namespace PayrollEvaluation06
    {
        static public class Calculations
        {
            public static double Add(double a, double b)
            {
                return a + b;
            }
    
            static public double Subtract(double a, double b)
            {
                return a - b;
            }
    
            public static double Multiply(double a, double b)
            {
                return a * b;
            }
    
            public static double Add5(double a, double b, double c, double d, double e)
            {
                return a + b + c + d + e;
            }
    
            public static double Multiply3(double a, double b, double c)
            {
                return a * b * c;
            }
        }
    }
  18. On the main menu, click Project -> Add Class...
  19. Change the name to TimeSheet
  20. Click Add
  21. Right-click inside the Code Editor -> Remove and Sort Usings
  22. Change the code as follows:
    namespace PayrollEvaluation06
    {
        public class TimeSheet
        {
            public double Monday { get; set; }
            public double Tuesday { get; set; }
            public double Wednesday { get; set; }
            public double Thursday { get; set; }
            public double Friday { get; set; }
    
            public TimeSheet()
            {
                Monday = 0.00;
                Tuesday = 0.00;
                Wednesday = 0.00;
                Thursday = 0.00;
                Friday = 0.00;
            }
    
            public TimeSheet(double mon, double tue,
                             double wed, double thu, double fri)
            {
                Monday = mon;
                Tuesday = tue;
                Wednesday = wed;
                Thursday = thu;
                Friday = fri;
            }
        }
    }
  23. In the Solution Explorer, right-click Form1.cs and click Rename
  24. Type PayrollPreparation (to get PayrollPreparation.cs) and press Enter
  25. Read the message box and press Enter twice (to access the form)
  26. Design the form as follows:

    Switching to a Boolean Value

    Control (Name) Text Other Properties
    GroupBox   Work Preparation  
    Label   Hourly Salary:  
    TextBox txtHourlySalary 0.00 TextAlign: Right
    CheckBox chkPaidOvertime Paid Overtime CheckAlign: MiddleRight
    Label   Monday  
    Label   Tuesday  
    Label   Wednesday  
    Label   Thursday  
    Label   Friday  
    TextBox txtMonday 0.00 Right
    TextBox txtTuesday 0.00 Right
    TextBox txtWednesday 0.00 Right
    TextBox txtThursday 0.00 Right
    TextBox txtFriday 0.00 Right
    Button btnCalculate Calculate  
    GroupBox   Pay Summary  
    Label   Time Worked:  
    TextBox txtTimeWorked Right
    Label   Overtime:  
    TextBox txtOvertime Right Right
    Label   Net Pay:
    TextBox txtNetPay Right
  27. Double-click the Calculate button
  28. Right-click inside the Code Editor and click Remove and Sort Usings

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.

Practical LearningPractical Learning: Switching to a Boolean Value

  1. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace PayrollEvaluation06
    {
        public partial class PayrollPreparation : Form
        {
            public PayrollPreparation()
            {
                InitializeComponent();
            }
    
            void EvaluateOvertimeSalary(TimeSheet ts, double hourlySalary)
            {
                double overtimePay;
                double overtime = 0.00;
                // mon + tue + wed + thu + fri
                double timeWorked = Calculations.Add5(ts.Monday, ts.Tuesday, ts.Wednesday, ts.Thursday, ts.Friday);
                double netPay = hourlySalary * timeWorked;
    
                if (timeWorked > 40.00)
                {
                    // timeWorked - 40.00
                    overtime = Calculations.Subtract(timeWorked, 40.00);
                    // hourlySalary * 1.50 * overtime
                    overtimePay = Calculations.Multiply3(hourlySalary, 1.50, overtime);
                    // (hourlySalary * 40.00) + overtimePay
                    netPay = Calculations.Add(Calculations.Multiply(hourlySalary, 40.00), overtimePay);
                }
    
                txtTimeWorked.Text = timeWorked.ToString("F");
                txtOvertime.Text = overtime.ToString("F");
                txtNetPay.Text = netPay.ToString("F");
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double mon = Convert.ToDouble(txtMonday.Text);
                double tue = Convert.ToDouble(txtTuesday.Text);
                double wed = Convert.ToDouble(txtWednesday.Text);
                double thu = Convert.ToDouble(txtThursday.Text);
                double fri = Convert.ToDouble(txtFriday.Text);
    
                double hSalary = Convert.ToDouble(txtHourlySalary.Text);
    
                TimeSheet record = new TimeSheet(mon, tue, wed, thu, fri);
    
                switch (chkPaidOvertime.Checked)
                {
                    case true:
                        EvaluateOvertimeSalary(record, hSalary);
                        break;
                    case false:
                        double timeWorked = Calculations.Add5(ts.Monday, ts.Tuesday, ts.Wednesday, ts.Thursday, ts.Friday);
    
                        txtTimeWorked.Text = timeWorked.ToString("F");
                        txtOvertime.Text = "0.00";
                        txtNetPay.Text = (timeWorked * hSalary).ToString("F");
                        break;
                }
            }
        }
    }
  2. To execute the project, press Ctrl + F5

    Switching to a Boolean Value

  3. In the Hourly Salary text box, type a decimal number such as 25.85
  4. In each days text box, type a decimal number between 0 and 8 but divisible by 0.50. Here are examples:

    Switching to a Boolean Value

  5. Click the Calculate button:

    Switching to a Boolean Value

  6. Click the Paid Overtime check box
  7. Click the Calculate button:

    Switching to a Boolean Value

  8. Close the form and return to your programming environment
  9. To create an enumeration, change the document as follows:
  10. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  11. In the list of projects templates, click Windows Forms App (.NET Framework)
  12. Click Next
  13. Change the project Name to Chemistry07
  14. Click Add
  15. On the main menu, click Project -> Add Class...
  16. Replace the name with Element
  17. Click Add
  18. Change the code as follows:
    namespace Chemistry07
    {
        public enum Phase
        {
            Gas,
            Liquid,
            Solid,
            Unknown
        }
        public class Element
        {
            public string Symbol       { get; set; }
            public string ElementName  { get; set; }
            public int    AtomicNumber { get; set; }
            public double AtomicWeight { get; set; }
            public Phase  Phase        { get; set; }
    
            public Element()                 {}
            public Element(int number)    => AtomicNumber = number;
            public Element(string symbol) => Symbol = symbol;
    
            public Element(int number, string symbol, string name, double mass, Phase phase)
            {
                ElementName = name;
                AtomicWeight = mass;
                Phase = phase;
                Symbol = symbol;
                AtomicNumber = number;
            }
        }
    }
  19. In the Solution Explorer, right-click Form1.cs -> Rename
  20. Type Chemistry to get Chemistry.cs
  21. Press Enter three times (to accept the name and access the form
  22. Design the form as follows:

    Introduction to Logical Operations

    Control (Name) Text
    Label   Enter Atomic #::
    TextBox txtValueEntered
    Button btnFind Find
    GroupBox   Element Detais
    Label   Atomic Number:
    TextBox txtAtomicNumber
    Label   Symbol:
    TextBox txtSymbol
    Label   Element Name:
    TextBox txtElementName
    Label   Atomic Weight:
    TextBox txtAtomicWeight
    Label   Phase:
    TextBox txtPhase
  23. Double-click the Find button
  24. Right-click inside the Code Editor and click Remove and Sort Usings

Switching Integral Values

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. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace Chemistry07
    {
        public partial class Chemistry : Form
        {
            public Chemistry()
            {
                InitializeComponent();
            }
    
            private void btnFind_Click(object sender, EventArgs e)
            {
                Element H = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas);
                Element He = new Element(2, "He", "Helium", 4.002602, Phase.Gas);
                Element Li = new Element(3, "Li", "Lithium", 6.94, Phase.Solid);
                Element Be = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid);
                Element B = new Element(5, "B", "Boron", 10.81, Phase.Solid);
                Element C = new Element(name: "Carbon", mass: 12.011, symbol: "C", number: 6, phase: Phase.Solid);
                Element N = new Element(7);
                N.Symbol = "N";
                N.AtomicWeight = 14.007;
                N.ElementName = "Nitrogen";
                N.Phase = Phase.Gas;
                Element O = new Element("O")
                {
                    AtomicNumber = 8,
                    ElementName = "Oxygen",
                    AtomicWeight = 15.999,
                    Phase = Phase.Gas
                };
                Element F = new Element("F") {  AtomicNumber = 9, ElementName = "Fluorine",
                                                AtomicWeight = 15.999,  Phase = Phase.Gas  };
                Element Ne = new Element("Ne")
                {
                    AtomicNumber = 10, ElementName = "Neon",
                    AtomicWeight = 20.1797, Phase = Phase.Gas
                };
                Element Na = new Element(11, "Na", "Sodium", 22.98976928, Phase.Solid);
                Element Mg = new Element(12, "Mg", "Magnesium", 24.305, Phase.Solid);
                Element Al = new Element(13, "Al", "Aluminium", 26.9815385, Phase.Solid);
                Element Si = new Element() { ElementName = "Silicon", AtomicWeight = 28.085, Symbol = "Si", AtomicNumber = 14, Phase = Phase.Solid };
                Element P = new Element() {
                    ElementName = "Phosphorus", AtomicWeight = 30.973761998,
                    Symbol = "P", AtomicNumber = 15, Phase = Phase.Solid };
                Element S = new Element(16, "S", "Sulfur", 32.06, Phase.Solid);
                Element Cl = new Element() { ElementName = "Chlorine", AtomicWeight = 35.446, Symbol = "Cl", AtomicNumber = 17, Phase = Phase.Gas };
                Element Ar = new Element() { ElementName = "Argon", AtomicWeight = 39.792, Symbol = "Ar", AtomicNumber = 18, Phase = Phase.Gas };
                Element K  = new Element() { ElementName = "Potassium", Symbol = "K", Phase = Phase.Solid, AtomicWeight = 39.0983, AtomicNumber = 19 };
                Element Ca = new Element() { Symbol = "Ca", Phase = Phase.Solid, AtomicNumber = 20, ElementName = "Calcium", AtomicWeight = 40.078 };
                Element Sc  = new Element() { AtomicNumber = 21, Symbol = "Sc", AtomicWeight = 44.9559085, Phase = Phase.Solid, ElementName = "Scandium" };
    
                Element selected = new Element();
                int number = int.Parse(txtValueEntered.Text);
    
                switch (number)
                {
                    case 20:
                        selected = Ca;
                        break;
                    case 12:
                        selected = Mg;
                        break;
                    case 5:
                        selected = B;
                        break;
                    case 17:
                        selected = Cl;
                        break;
                    case 15:
                        selected = P;
                        break;
                    case 6:
                        selected = C;
                        break;
                    case 21:
                        selected = Sc;
                        break;
                    case 7:
                        selected = N;
                        break;
                    case 9:
                        selected = F;
                        break;
                    case 2:
                        selected = He;
                        break;
                    case 10:
                        selected = Ne;
                        break;
                    case 11:
                        selected = Na;
                        break;
                    case 4:
                        selected = Be;
                        break;
                    case 13:
                        selected = Al;
                        break;
                    case 3:
                        selected = Li;
                        break;
                    case 19:
                        selected = K;
                        break;
                    case 14:
                        selected = Si;
                        break;
                    case 16:
                        selected = S;
                        break;
                    case 8:
                        selected = O;
                        break;
                    case 18:
                        selected = Ar;
                        break;
                }
    
                txtSymbol.Text = selected.Symbol;
                txtAtomicNumber.Text = selected.AtomicNumber.ToString();
                txtElementName.Text = selected.ElementName;
                txtAtomicWeight.Text = selected.AtomicWeight.ToString();
                txtPhase.Text = selected.Phase.ToString();
            }
        }
    }
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Multiple Conditions

  3. In the top text box, type a number between 1 (included) and 21 (included). Here is an example:

    Introduction to Multiple Conditions

  4. Click the Find button:

    Introduction to Boolean Disjunctions

  5. Close the form and return to your programming environment
  6. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  7. In the list of projects templates, click Windows Forms App (.NET Framework)
  8. Click Next
  9. Change the project Name to CompoundInterest3
  10. Click Create
  11. On the main menu, click Project -> Add New Item...
  12. In the left list, under Visual C# Items, click Code and, in the middle list, click Code File
  13. Change the file Name to Frequency
  14. Click Add
  15. In the empty document, type the following code:
    namespace CompoundInterest3
    {
        public enum CompoundFrequency
        {
            Daily,
            Weekly,
            Monthly,
            Quaterly,
            Semiannually,
            Annually
        }
    }
  16. In the Solution Explorer, right-click Form1.cs -> Rename
  17. Type CompoundInterest to get CompoundInterest.cs
  18. Press Enter three times
  19. Design the form as follows:

    Introducing if...else if Conditions

    Control (Name) Text Other Properties
    Label   Principal:  
    TextBox txtPrincipal 0.00 TextAlign: Right
    Label   Interest Rate:  
    TextBox txtInterest Rate 0.00 TextAlign: Right
    Label   %  
    Label   Periods:  
    TextBox txtPeriods 0 TextAlign: Right
    Label   Years:  
    GroupBox   Compound Frequency  
    RadioButton rdoDaily Daily CheckAlign: MiddleRight
    RadioButton rdoQuaterly Quaterly CheckAlign: MiddleRight
    RadioButton rdoWeekly Weekly CheckAlign: MiddleRight
    RadioButton rdoSemiannually Semiannually CheckAlign: MiddleRight
    RadioButton rdoMonthly Monthly CheckAlign: MiddleRight
    RadioButton rdoAnnually Annually CheckAlign: MiddleRight
    Button btnCalculate Calculate  
    Label   Interest Earned:  
    TextBox txtInterestEarned   TextAlign: Right
    Label   Future Value:  
    TextBox txtFutureValue   TextAlign: Right
  20. Double-click the Calculate button
  21. Right-click the Code Editor and click Remove and Sort Usings

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. Implement the event as follows:
    using System;
    using System.Windows.Forms;
    
    namespace CompoundInterest3
    {
        public partial class CompoundInterest : Form
        {
            public CompoundInterest()
            {
                InitializeComponent();
            }
    
            private void btnCalculate_Click(object sender, EventArgs e)
            {
                double frequency = 0.00;
                double principal = Convert.ToDouble(txtPrincipal.Text);
                double interestRate = Convert.ToDouble(txtInterestRate.Text);
                double periods = Convert.ToDouble(txtPeriods.Text);
    
                double iRate = interestRate / 100.00;
                CompoundFrequency compounding = CompoundFrequency.Daily;
    
                if (rdoDaily.Checked)
                    compounding = CompoundFrequency.Daily;
                if (rdoWeekly.Checked)
                    compounding = CompoundFrequency.Weekly;
                if (rdoMonthly.Checked)
                    compounding = CompoundFrequency.Monthly;
                if (rdoQuaterly.Checked)
                    compounding = CompoundFrequency.Quaterly;
                if (rdoSemiannually.Checked)
                    compounding = CompoundFrequency.Semiannually;
                if (rdoAnnually.Checked)
                    compounding = CompoundFrequency.Annually;
    
                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;
    
                txtInterestEarned.Text = interestEarned.ToString("F");
                txtFutureValue.Text = futureValue.ToString("F");
            }
        }
    }
  2. To execute the application to test it, on the main menu, click Debug -> Start Without Debugging:

    Switching an Enumeration

  3. In the Principal text box, type a number such as 3685
  4. In the Interest Rate text box, type a number such as 10.75

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

    Switching an Enumeration

  7. Click the Calculate button:

    Switching an Enumeration

  8. Close the form and return to your programming environment
  9. Close your programming environment

Previous Copyright © 2001-2021, FunctionX Next