Options on Conditional Switches
Options on Conditional Switches
Considering Unknown Cases
Switching to a Null Case
When working on a switch statement, you may have a situation where the variable considered is not holding a known value or its value is clearly null. In this situation, the C# language allows you to consider a case that is null. To do this, in the switch statement, create a case whose value is null. Here is an example:
using System.Windows.Forms; namespace Chemistry { public partial class Form1 : Form { public Form1() { InitializeComponent(); Element elm = Create(); txtSymbol.Text = elm.Symbol; txtAtomicNumber.Text = elm.AtomicNumber.ToString(); txtElementName.Text = elm.ElementName; txtAtomicWeight.Text = elm.AtomicWeight.ToString(); txtPhase.Text = elm.Phase.ToString(); } Element Create() { int? number = null; Element selected = null; Element b = new Element(5, "B", "Boron", 10.81, Phase.Solid); 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); switch (number) { case 2: selected = he; break; case 3: selected = li; break; case 4: selected = be; break; case 5: selected = b; break; case null: selected = h; break; } return selected; } } 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(int number, string symbol, string name, double mass, Phase phase) { ElementName = name; AtomicWeight = mass; Phase = phase; Symbol = symbol; AtomicNumber = number; } } }
By the way, the null case can be the first, it can be the last, or it can appear in any position within the switch statment.
Switching to the default Outcome
When considering the possible outcomes of a switch statement, 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 formula of the switch statement that considers the default case is:
switch(expression) { case choice1: statement1; break; case choice2: statement2; break; case choice-n: statement-n; break; default: default-statement; break; }
In some languages, the default section doesn't require 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.
Practical Learning: Switching to a Default Outcome
Nothing Utah Illinois Indiana Michigan Colorado Pennsylvania North Carolina
Control | (Name) | Text | TextAlign |
Label | Gross Salary: | ||
TextBox | txtGrossSalary | 0 | Right |
Label | State: | ||
ComboBox | cbxStates | ||
Button | btnCalculate | Calculate | |
Label | txtEmployeeResidence | ||
TextBox | txtEmployeeResidence | Right | |
Label | txtIncomeTax | ||
TextBox | Right | ||
Label | Net Pay: | ||
TextBox | txtNetPay | Right |
using System; using System.Windows.Forms; namespace PayrollEvaluation06 { public partial class PayrollEvaluation : Form { public PayrollEvaluation() { InitializeComponent(); } private void btnCalculate_Click(object sender, EventArgs e) { double taxes = 0.00; string residence = ""; 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; default: taxes = 0.00; residence = ""; break; } txtEmployeeResidence.Text = residence; txtStateIncomeTax.Text = taxes.ToString("F"); txtNetPay.Text = (salary - taxes).ToString("F"); } } }
namespace Chemistry08 { 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; } } }
Control | (Name) | Text |
Label | Enter Atomic Number:: | |
TextBox | txtNumberEntered | |
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 |
Considering Default and Null Cases
When creating a switch statement, you should predict as many cases as possible. We already know that you can create a default case that would embrace the value that matches none of the others; but the default case assumes that there is a valid value that none of the other cases is holding. We saw that this is not always the case: there could be an unknown or invalid value. For example, you can consider a series of numbers from 10, in which case 12 is not included but 12 is a valid value; but a null case would mean that you don't have a number at all. For this type of scenario, you should consider using both a null and a default cases. By the way, those cases can appear in any order.
Practical Learning: Considering Default and Null Cases
using System;
using System.Windows.Forms;
namespace Chemistry08
{
public partial class Chemistry : Form
{
public Chemistry()
{
InitializeComponent();
}
Element SelectElement()
{
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() { AtomicWeight = 35.446, Symbol = "Cl", ElementName = "Chlorine", 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 Ti = new Element() { ElementName = "Titanium", AtomicWeight = 47.8671, Symbol = "Ti", AtomicNumber = 22, Phase = Phase.Solid };
Element selected;
int? number = null;
if (txtNumberEntered.Text == "")
number = null;
else
number = int.Parse(txtNumberEntered.Text);
switch (number)
{
case 8:
selected = O;
break;
case 19:
selected = K;
break;
case 7:
selected = N;
break;
case 9:
selected = F;
break;
case 16:
selected = S;
break;
case 3:
selected = Li;
break;
case 6:
selected = C;
break;
case 10:
selected = Ne;
break;
case 5:
selected = B;
break;
default:
selected = H;
break;
case null:
selected = new Element(0, "", "Known", 0.00, Phase.Unknown); ;
break;
case 11:
selected = Na;
break;
case 2:
selected = He;
break;
case 12:
selected = Mg;
break;
case 4:
selected = Be;
break;
case 13:
selected = Al;
break;
case 21:
selected = Sc;
break;
case 14:
selected = Si;
break;
case 20:
selected = Ca;
break;
case 15:
selected = P;
break;
case 22:
selected = Ti;
break;
case 18:
selected = Ar;
break;
case 17:
selected = Cl;
break;
}
return selected;
}
void Display(Element ce)
{
txtSymbol.Text = ce.Symbol;
txtAtomicNumber.Text = ce.AtomicNumber.ToString();
txtElementName.Text = ce.ElementName;
txtAtomicWeight.Text = ce.AtomicWeight.ToString();
txtPhase.Text = ce.Phase.ToString();
}
private void btnFind_Click(object sender, EventArgs e)
{
Element elm = SelectElement();
Display(elm);
}
}
}
Nothing Utah Texas Alaska Nevada Florida Indiana Wyoming Illinois Michigan Colorado Tennessee Washington Pennsylvania South Dakota New Hampshire North Carolina
Cases Combinations
Introductions
Although each case must consider only one value, you may have a situation where different case values must deal with the same outcome. In this case, you can combine those cases. To do this, type case followed by its value and a colon. On the next line, create another case with its value and colon. You can continue that for each value that fits that group. Then write the common code of those cases and end the section with the required break keyword and its semicolon.
Practical Learning: Combining Cases in a Switch
using System; using System.Windows.Forms; namespace PayrollEvaluation06 { public partial class PayrollEvaluation : Form { public PayrollEvaluation() { InitializeComponent(); } private void btnCalculate_Click(object sender, EventArgs e) { double taxes = 0.00; string residence = ""; 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 "Alaska": case "Florida": // Two of the 9 states that don't collect an income tax taxes = 0.00; residence = "No Income Tax"; 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 "Nevada": case "New Hampshire": case "Tennessee": case "Texas": // Four other states that don't collect an income tax taxes = 0.00; residence = "Income Tax Not Collected"; 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 "South Dakota": case "Washington": case "Wyoming": // Three other states that don't collect an income tax taxes = 0.00; residence = "Income Tax Not Paid"; 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; default: taxes = 0.00; residence = ""; break; } txtEmployeeResidence.Text = residence; txtStateIncomeTax.Text = taxes.ToString("F"); txtNetPay.Text = (salary - taxes).ToString("F"); } } }
Nesting a Conditional Statement in a Case
Each case of a switch statement has its own body in which you can create a conditional statement. This is referred to as nesting.
Practical Learning: Nesting a Conditional Statement in a Case
Control | (Name) | Text | Other Properties |
Label | Gross Salary: | ||
TextBox | txtGrossSalary | 0 | TextAlign: Right |
Label | Filing As: | ||
ComboBox | cbxFilingAs | Items:
Single Married |
|
Label | Exemptions: | ||
TextBox | txtExemptions | ||
Button | btnCalculate | Calculate | |
Label | Filing Status: | ||
TextBox | txtFilingStatus | TextAlign: Right | |
Label | Allowances | ||
TextBox | txtAllowances | TextAlign: Right | |
Label | Taxable Gross Wages: | ||
TextBox | txtTaxableGrossWages | TextAlign: Right | |
Label | Federal Income Tax: | ||
TextBox | txtFederalIncomeTax | TextAlign: Right |
using System;
using System.Windows.Forms;
namespace PayrollPreparation7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
double withheldAmount = 0;
double allowanceRate = 77.90;
double salary = double.Parse(txtGrossSalary.Text);
string filingStatus = cbxFilingStatus.Text;
int exemptions = int.Parse(txtExemptions.Text);
double withheldingAllowances = allowanceRate * exemptions;
double taxableGrossWages = salary - withheldingAllowances;
switch (filingStatus)
{
case "Single":
if (taxableGrossWages <= 44)
{
withheldAmount = 0;
}
else if ((taxableGrossWages > 44.00) && (taxableGrossWages <= 224.00))
{
withheldAmount = (taxableGrossWages - 44.00) * 10.00 / 100;
}
else if ((taxableGrossWages > 224.00) && (taxableGrossWages <= 774.00))
{
withheldAmount = 18.00 + ((taxableGrossWages - 224.00) * 15.00 / 100);
}
else if ((taxableGrossWages > 774.00) && (taxableGrossWages <= 1812.00))
{
withheldAmount = 100.50 + ((taxableGrossWages - 774.00) * 25.00 / 100);
}
else if ((taxableGrossWages > 1812.00) && (taxableGrossWages <= 3730))
{
withheldAmount = 360.00 + ((taxableGrossWages - 1812.00) * 28.00 / 100);
}
else if ((taxableGrossWages > 3730.00) && (taxableGrossWages <= 8058.00))
{
withheldAmount = 897.04 + ((taxableGrossWages - 3730.00) * 33.00 / 100);
}
else if ((taxableGrossWages > 8058.00) && (taxableGrossWages <= 8090.00))
{
withheldAmount = 2325.28 + ((taxableGrossWages - 8058) * 35.00 / 100);
}
else // if (taxableGrossWages > 8090.00)
{
withheldAmount = 2336.48 + ((taxableGrossWages - 8090.00) * 39.60 / 100);
}
break;
case "Married":
if (taxableGrossWages <= 166.00)
{
withheldAmount = 0;
}
else if ((taxableGrossWages > 166.00) && (taxableGrossWages <= 525.00))
{
withheldAmount = (taxableGrossWages - 166.00) * 10.00 / 100;
}
else if ((taxableGrossWages > 525.00) && (taxableGrossWages <= 1626.00))
{
withheldAmount = 35.90 + ((taxableGrossWages - 525.00) * 15.00 / 100);
}
else if ((taxableGrossWages > 1626.00) && (taxableGrossWages <= 3111.00))
{
withheldAmount = 201.05 + ((taxableGrossWages - 1626.00) * 25.00 / 100);
}
else if ((taxableGrossWages > 3111.00) && (taxableGrossWages <= 4654.00))
{
withheldAmount = 572.30 + ((taxableGrossWages - 3111.00) * 28.00 / 100);
}
else if ((taxableGrossWages > 4654.00) && (taxableGrossWages <= 8180.00))
{
withheldAmount = 1004.34 + ((taxableGrossWages - 4654.00) * 33.00 / 100);
}
else if ((taxableGrossWages > 8160.00) && (taxableGrossWages <= 9218.00))
{
withheldAmount = 2167.92 + ((taxableGrossWages - 8180.00) * 35.00 / 100);
}
else // if (taxableGrossWages > 9218)
{
withheldAmount = 2531.22 + ((taxableGrossWages - 9218.00) * 39.60 / 100);
}
break;
}
txtFilingStatus.Text = filingStatus;
txtAllowances.Text = withheldingAllowances.ToString("F");
txtTaxableGrossWages.Text = taxableGrossWages.ToString("F");
txtFederalIncomeTax.Text = withheldAmount.ToString("F");
}
}
}
Pattern Matching
When Switching a Value
So far, we have seen that, when you are setting up a switch statement, create the desired case clauses in the switch section. The case keyword can be followed by either a constant value or an expression. Here are examples:
switch (number) { case 1: selected = h; break; case 2: selected = he; break; case 3: selected = li; break; }
Pattern matching consists of applying a condition to a case. In a case of a switch statement, you can include a conditional statement that compares its value to another to actually validate the case. This is done using the when keyword. The formula to follow is:
case value-or-expression when logical-expression: statement(s)
As mentioned already, the case is followed by a constant or an expression, The new keyword is when. It is followed by a logical expression.
When Switching a Variable
After a case keyword, you can declare a variable of the same type as the value used in the parentheses of switch(). Follow the variable with the when keyword followed by a logical expression that equates the variable to the case value. The variable is "visible" only with its case. Therefore, you can use the same variable in different case sections.
When Patterning a Conditional Statement
The when expression is used to apply a conditional statement. It can consist of an expression that uses any of the Boolean operators we are familiar with. It may look as follows:
switch(number) { case value-or-expression when number > 8: statement(s); break; }
Patterning Different Types of Values
When using a switch statement, the values involved must be of the same type or compatible. Otherwise, you can find a way to convert them.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2021, FunctionX | Next |
|