Foundations of Switching a Case

Introduction

By now, we know that a conditional statement is a section of code that performs one or more comparisons on values and allows you to make a decision. In previous lessons, we performed those comparisons using logical operators and special keywords to make decisions. There are even more options to assist you in making decisions

Practical LearningPractical Learning: Switching a String

  1. Start Microsoft Visual Studio and create a new ASP.NET Core Web App named TaxPreparation04. Uncheck the Configure For HTTPS check box
  2. In the Solution Explorer, expand wwwroot
  3. In the Solution Explorer, under wwwroot, right-click css -> Add -> New Item...
  4. In the left list of the Add New Item dialog box, under Visual C#, expand ASP.NET Core. Expand Web, and click Content
  5. In the middle list, click Style Sheet
  6. Change the file Name to TaxPreparation
  7. Click Add
  8. Change the document as follows:
    body {
    }
    
    .delimiter   { margin:      auto;
                   width:       450px; }
    .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  9. In the Solution Explorer, under Pages, expand Shared
  10. In the Solution Explorer, under Pages and under Shared, double-click _Layout.cshtml
  11. Change the document as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - DelTax Services</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/TaxPreparation03.styles.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/css/TaxPreparation.css" asp-append-version="true" />
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
                <div class="container">
                    <a class="navbar-brand" asp-area="" asp-page="/Index">DelTax Home</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                <p class="text-center common-font">&copy; 2022 - DelTax Services - <a asp-area="" asp-page="/Privacy">Privacy</a></p>
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
  12. In the Solution Explorer, expand Pages
  13. In the Solution Explorer, under Pages, double-click Index.cshtml
  14. Change the document as follows:
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    @{
        string strNetPay = "";
        string strTaxRate = "";
        string strTaxAmount = "";
    
        string strStateName = "";
        string strGrossSalary = "";
    
        if (Request.HasFormContentType)
        {
            double taxRate     = 0.00;
            double grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
    
            strStateName       = Request.Form["selStates"];
            
            double taxAmount   = grossSalary * taxRate / 100.00;
            double netPay      = grossSalary - taxAmount;
    
            strGrossSalary     = $"{grossSalary:F}";
            strTaxRate         = $"{taxRate/100:P}";
            strTaxAmount       = $"{taxAmount:F}";
            strNetPay          = $"{(grossSalary - taxAmount):F}";
        }
    }
    
    <h1 class="text-center common-font">- State Income Tax -</h1>
    <hr />
    <div class="delimiter common-font">
        <form name="frmTaxPreparation" method="post">
            <table align="center">
                <tr>
                    <td style="width: 200px">Select a State:</td>
                    <td>
                        <select id="selStates" name="selStates">
                            <option value="Alaska">Alaska</option>
                            <option value="Arkansas">Arkansas</option>
                            <option value="Colorado">Colorado</option>
                            <option value="Florida">Florida</option>
                            <option value="Georgia">Georgia</option>
                            <option value="Illinois">Illinois</option>
                            <option value="Indiana">Indiana</option>
                            <option value="Kentucky">Kentucky</option>
                            <option value="Massachusetts">Massachusetts</option>
                            <option value="Michigan">Michigan</option>
                            <option value="Missouri">Missouri</option>
                            <option value="Mississippi">Mississippi</option>
                            <option value="Nevada">Nevada</option>
                            <option value="New Hampshire">New Hampshire</option>
                            <option value="North Carolina">North Carolina</option>
                            <option value="Pennsylvania">Pennsylvania</option>
                            <option value="South Dakota">South Dakota</option>
                            <option value="Tennessee">Tennessee</option>
                            <option value="Texas">Texas</option>
                            <option value="Utah">Utah</option>
                            <option value="Washington">Washington</option>
                            <option value="Wyoming">Wyoming</option>
                        </select>
                    </td>
                </tr>
            </table>
    
        <hr />
        
        <table class="table">
            <tr>
                <td width="125"><label for="txtGrossSalary">Gross Salary:</label></td>
                <td><input type="text" id="txtGrossSalary" name="txtGrossSalary" value="@strGrossSalary" class="form-control" /></td>
            </tr>
            <tr>
                <td></td>
                <td class="pcenter"><input type="submit" value="Evaluate Taxes" class="btn-primary" /></td>
            </tr>
        </table>
        </form>
        
        <table class="table">
            <tr>
                <td width="125">Gross Salary:</td>
                <td>@strGrossSalary</td>
            </tr>
            <tr>
                <td>State Name:</td>
                <td>@strStateName</td>
            </tr>
            <tr>
                <td>Tax Rate:</td>
                <td>@strTaxRate</td>
            </tr>
            <tr>
                <td>Tax Amount:</td>
                <td>@strTaxAmount</td>
            </tr>
            <tr>
                <td>Net Pay:</td>
                <td>@strNetPay</td>
            </tr>
        </table>
    </div>
  15. To execute the project, on the main menu, click Debug -> Start Without Debugging

    Conditional Switches

  16. In the Select a State combo box, select Florida
  17. In the Gross Salary text box, type 1558.85
  18. Click the Evaluate Taxes button:

    Conditional Switches

  19. Change the State to Kentucky
  20. Click the Evaluate Taxes button:

    Conditional Switches

  21. Return to your programming environment

A Case for a Conditional Selection

In a typical application, you have many comparisons to make. Some comparisons involve many variables but some comparisons are performed on only one variable and values. This means that you may have a situation where you want to compare one variable to many values. This time, you create a list of comparisons, then select which outcome applies to the conclusion you need to establish.

To perform a series of comparisons of one variable with one or more values, you use a keyword named switch. Like most comparison operators, including if that we saw in previous lessons, the switch keyword requires parentheses, as in switch(). In the parentheses, you must type the existing name of the variable on which you want to perform comparisons. In the previous lessons, we saw that the if operator doesn't require curly brackets if its code includes only one line of code but requires curly brackets if its body includes more than one line of code. The switch() conditional statement always uses more than one line of code. Therefore, it requires a body delimited by curly brackets:

switch(variable-name)
{
}

Once again, the section from the opening curly bracket ({) to the closing curly bracket (}) is the body of the switch() conditional statement. In that body, you must create one or more sections that would perform the necessary selections. Each section is created with a keyword named case. The case keyword creates its own section that includes the actual processing that must occur. As a result, this keyword must have its own delimiting body. Exceptionally (this is the only C# topic that functions like that), the body of a case section starts with a colon (:) and ends with a keyword named break, which is a statement and therefore must end with a semicolon. Therefore, the formula to create a switch statement is:

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

As mentioned above, you start with the switch() statement that is followed by a body delimited by curly brackets. In the parentheses of switch(), you can put the name of a variable. That variable must already exist and must hold a valid value. As we will see in later sections. The value in the parentheses of switch() can also be an expression that can be evaluated to a valid value. The body of the switch statement contains one or more sections that each starts with the case keyword. Each case section uses a body from a colon to a break; line. In that body, you will write code to process the outcome of that case or selection.

The switch statement accepts different types of expressions or 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.

In most cases, a switch statement behaves like an if conditional statement except that an if conditional statement may use fewer lines of code. Consider the following code that uses an if conditional statement:

@page
@model Valuable.Pages.ArithmeticModel

@{
    int number = 248;
    string conclusion = "That number is not right.";
    
    if(number == 248)
        conclusion = "That number is correct.";
}

<h3>Arithmetic</h3>
<hr />
<p>Number: @number</p>
<p>@conclusion</p>
<hr />

This would produce:

Arithmetic

Number: 248

That number is correct.

The same code can be written with a switch statement as follows:

@page
@model Valuable.Pages.ArithmeticModel

@{
    int number = 248;
    string conclusion = "That number is not right.";
    
    switch (number)
    {
        case 248:
            conclusion = "That number is correct.";
            break;
    }
}

<h3>Arithmetic</h3>
<hr />
<p>Number: @number</p>
<p>@conclusion</p>
<hr />

Switching a String

Besides a natural number, a switch statement can perform its case comparisons on a string value, such as a variable that holds a string value or an expression that produces a string. This means that each case must consider a possible value that the variable or expression may hold.

We know that an if conditional statement can use one or more else options. Here is an example:

@page
@model Valuable.Pages.PayrollEvaluationModel

@{
    string frequency      = "Unknown";
    double incomeTax      =  0.00;
    string strIncomeTax   = "0.00";
    string strGrossSalary = "0.00";
    
    if (Request.HasFormContentType)
    {
        frequency = Request.Form["rdoPayrollFrequency"];
        double grossSalary = double.Parse(Request.Form["txtGrossSalary"]);

        if(frequency == "Weekly")
            incomeTax = 271.08 + (grossSalary * 24 / 100);
        else if(frequency == "Biweekly")
            incomeTax = 541.82 + (grossSalary * 24 / 100);
        else if(frequency == "Semimonthly")
            incomeTax = 587.12 + (grossSalary * 24 / 100);
        else if(frequency == "Monthly")
            incomeTax = 1174.12 + (grossSalary * 24 / 100);

        strGrossSalary = $"{grossSalary:F}";
        strIncomeTax   = $"{incomeTax:F}";
    }
}

<h3>Payroll Evaluation</h3>
<hr />
@using(Html.BeginForm("form-name", "controller-name", FormMethod.Post))
{
    <table class="table common-font">
        <tr>
            <td width="125">@Html.Label("txtGrossSalary", "Gross Salary:", new { @class = "" })</td>
            <td>@Html.TextBox("txtGrossSalary", @strGrossSalary, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Payroll Frequency:</td>
            <td>@Html.RadioButton("rdoPayrollFrequency", "Weekly") Weekly</td>
        </tr>
        <tr>
            <td></td>
            <td>@Html.RadioButton("rdoPayrollFrequency", "Biweekly") Biweekly</td>
        </tr>
        <tr>
            <td></td>
            <td>@Html.RadioButton("rdoPayrollFrequency", "Semimonthly") Semimonthly</td>
        </tr>
        <tr>
            <td></td>
            <td>@Html.RadioButton("rdoPayrollFrequency", "Monthly") Monthly</td>
        <tr>
            <td></td>
            <td class="pcenter"><input type="submit" value="Evaluate Taxes" class="btn-primary" /></td>
        </tr>
    </table>
}
           
<h3>Payroll Evaluation</h3>

<hr />

<table class="table">
    <tr>
        <td width="125">Gross Salary:</td>
        <td>@strGrossSalary</td>
    </tr>
    <tr>
        <td>Payroll Frequency:</td>
        <td>@frequency</td>
    </tr>
    <tr>
        <td>Income Tax:</td>
        <td>@strIncomeTax</td>
    </tr>
</table>

Here is an example of running the program:

Conditional Switches

In this case, the switch statement can use a string and each case can use a string value. Here is an example:

@page
@model Valuable.Pages.PayrollEvaluationModel

@{
    string frequency      = "Unknown";
    double incomeTax      =  0.00;
    string strIncomeTax   = "0.00";
    string strGrossSalary = "0.00";
    
    if (Request.HasFormContentType)
    {
        frequency = Request.Form["rdoPayrollFrequency"];
        double grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
        
        switch(frequency)
        {
            case "Weekly":
                incomeTax = 271.08 + (grossSalary * 24 / 100);
                break;
            case "Biweekly":
                incomeTax = 541.82 + (grossSalary * 24 / 100);
                break;
            case "Semimonthly":
                incomeTax = 587.12 + (grossSalary * 24 / 100);
                break;
            case "Monthly":
                incomeTax = 1174.12 + (grossSalary * 24 / 100);
                break;
        }

        strGrossSalary = $"{grossSalary:F}";
        strIncomeTax   = $"{incomeTax:F}";
    }
}

<h3>Payroll Evaluation</h3>
<hr />
@using(Html.BeginForm("form-name", "controller-name", FormMethod.Post))
{
    <table class="table common-font">
        <tr>
            <td width="125">@Html.Label("txtGrossSalary", "Gross Salary:", new { @class = "" })</td>
            <td>@Html.TextBox("txtGrossSalary", @strGrossSalary, new { @class = "form-control" })</td>
        </tr>
        <tr>
            <td>Payroll Frequency:</td>
            <td>@Html.RadioButton("rdoPayrollFrequency", "Weekly") Weekly</td>
        </tr>
        <tr>
            <td></td>
            <td>@Html.RadioButton("rdoPayrollFrequency", "Biweekly") Biweekly</td>
        </tr>
        <tr>
            <td></td>
            <td>@Html.RadioButton("rdoPayrollFrequency", "Semimonthly") Semimonthly</td>
        </tr>
        <tr>
            <td></td>
            <td>@Html.RadioButton("rdoPayrollFrequency", "Monthly") Monthly</td>
        <tr>
            <td></td>
            <td class="pcenter"><input type="submit" value="Evaluate Taxes" class="btn-primary" /></td>
        </tr>
    </table>
}
           
<h3>Payroll Evaluation</h3>

<hr />

<table class="table">
    <tr>
        <td width="125">Gross Salary:</td>
        <td>@strGrossSalary</td>
    </tr>
    <tr>
        <td>Payroll Frequency:</td>
        <td>@frequency</td>
    </tr>
    <tr>
        <td>Income Tax:</td>
        <td>@strIncomeTax</td>
    </tr>
</table>

Here is an example of running the program:

Conditional Switches

Practical LearningPractical Learning: Switching by Some Strings

  1. Change the document as follows:
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    @{
        string strNetPay = "";
        string strTaxRate = "";
        string strTaxAmount = "";
    
        string strStateName = "";
        string strGrossSalary = "";
    
        if (Request.HasFormContentType)
        {
            double taxRate     = 0.00;
            double grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
    
            strStateName       = Request.Form["selStates"];
            
            switch (strStateName)
            {
                case "Colorado":
                    taxRate   = 4.63;
                    break;
                case "Florida":
                    taxRate   = 0.00;
                    break;
                case "Illinois":
                    taxRate   = 4.95;
                    break;
                case "Indiana":
                    taxRate   = 3.23;
                    break;
                case "Kentucky":
                    taxRate   = 5.00;
                    break;
                case "Massachusetts":
                    taxRate   = 5.00;
                    break;
                case "Michigan":
                    taxRate   = 4.25;
                    break;
                case "North Carolina":
                    taxRate   = 5.25;
                    break;
                case "New Hampshire":
                    taxRate   = 5.00;
                    break;
                case "Nevada":
                    taxRate   = 0.00;
                    break;
                case "Pennsylvania":
                    taxRate   = 3.07;
                    break;
                case "Tennessee":
                    taxRate = 1.00;
                    break;
                case "Texas":
                    taxRate   = 0.00;
                    break;
                case "Utah":
                    taxRate   = 4.95;
                    break;
                case "Washington":
                    taxRate   = 0.00;
                    break;
                case "Wyoming":
                    taxRate   = 0.00;
                    break;
            }
    
            double taxAmount   = grossSalary * taxRate / 100.00;
            double netPay      = grossSalary - taxAmount;
    
            strGrossSalary     = $"{grossSalary:F}";
            strTaxRate         = $"{taxRate/100:P}";
            strTaxAmount       = $"{taxAmount:F}";
            strNetPay          = $"{(grossSalary - taxAmount):F}";
        }
    }
    
    <h1 class="text-center common-font">- State Income Tax -</h1>
    <hr />
    <div class="delimiter common-font">
        <form name="frmTaxPreparation" method="post">
            <table align="center">
                <tr>
                    <td style="width: 200px">Select a State:</td>
                    <td>
                        <select id="selStates" name="selStates">
                            <option value="Alaska">Alaska</option>
                            <option value="Arkansas">Arkansas</option>
                            <option value="Colorado">Colorado</option>
                            <option value="Florida">Florida</option>
                            <option value="Georgia">Georgia</option>
                            <option value="Illinois">Illinois</option>
                            <option value="Indiana">Indiana</option>
                            <option value="Kentucky">Kentucky</option>
                            <option value="Massachusetts">Massachusetts</option>
                            <option value="Michigan">Michigan</option>
                            <option value="Missouri">Missouri</option>
                            <option value="Mississippi">Mississippi</option>
                            <option value="Nevada">Nevada</option>
                            <option value="New Hampshire">New Hampshire</option>
                            <option value="North Carolina">North Carolina</option>
                            <option value="Pennsylvania">Pennsylvania</option>
                            <option value="South Dakota">South Dakota</option>
                            <option value="Tennessee">Tennessee</option>
                            <option value="Texas">Texas</option>
                            <option value="Utah">Utah</option>
                            <option value="Washington">Washington</option>
                            <option value="Wyoming">Wyoming</option>
                        </select>
                    </td>
                </tr>
            </table>
            
            <hr />
        
            <table class="table">
                <tr>            
                    <td width="125"><label for="txtGrossSalary">Gross Salary:</label></td>
                    <td><input type="text" id="txtGrossSalary" name="txtGrossSalary" value="@strGrossSalary" class="form-control" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td class="pcenter"><input type="submit" value="Evaluate Taxes" class="btn-primary" /></td>
                </tr>
            </table>
        </form>
        
        <table class="table">
            <tr>
                <td width="125">Gross Salary:</td>
                <td>@strGrossSalary</td>
            </tr>
            <tr>
                <td>State Name:</td>
                <td>@strStateName</td>
            </tr>
            <tr>
                <td>Tax Rate:</td>
                <td>@strTaxRate</td>
            </tr>
            <tr>
                <td>Tax Amount:</td>
                <td>@strTaxAmount</td>
            </tr>
            <tr>
                <td>Net Pay:</td>
                <td>@strNetPay</td>
            </tr>
        </table>
    </div>
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. If the browser presents a Resend button, click it. Otherwise, refresh the browser
  4. In the Select a State combo box, selecte Colorado
  5. Make sure the Gross Salary text box is displaying 1558.85 (if not, set the salary to that value).
    Click the Evaluate Taxes button:

    Conditional Switches

  6. Change the State to Kentucky
  7. Click the Evaluate Taxes button:

    Conditional Switches

  8. Change the State to North Carolina
  9. Click the Evaluate Taxes button:

    Conditional Switches

  10. Return to your programming environment
  11. Start a new ASP.NET Core Web App named PayrollPreparation3. Uncheck the Configure for HTTPS check box
  12. In the Solution Explorer, expand wwwroot
  13. In the Solution Explorer, under wwwroot, right-click css -> Add -> New Item...
  14. In the left list of the Add New Item dialog box, under Visual C#, expand ASP.NET Core. Expand Web, and click Content
  15. In the middle list, click Style Sheet
  16. Change the file Name to PayrollEvaluation
  17. Click Add
  18. Change the document as follows:
    body {
    }
    
    .delimiter   { margin:      auto;
                   width:       450px; }
    .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; }
  19. In the Solution Explorer, under Pages, expand Shared
  20. In the Solution Explorer, under Pages and under Shared, double-click _Layout.cshtml
  21. Change the document as follows:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"] - Payroll Preparation</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/PayrollPreparation3.styles.css" asp-append-version="true" />
        <link rel="stylesheet" href="~/css/PayrollEvaluation.css" asp-append-version="true" />
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
                <div class="container">
                    <a class="navbar-brand" asp-area="" asp-page="/Index">Payroll Preparation</a>
                    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted">
            <div class="container">
                <p class="text-center common-font">&copy; 2022 - Payroll Preparation - <a asp-area="" asp-page="/Privacy">Privacy</a></p>
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
  22. In the Solution Explorer, expand Pages
  23. In the Solution Explorer, under Pages, double-click Index.cshtml

Conditionally Switching

Introduction

We saw that a switch conditional statement can process natural numbers and strings. It can also process Boolean values or logical expression. To proceed, you can write a Boolean variable or an expression that produces a Boolean value in the parentheses of switch(). Then, one case can consider a true value and another case would consider a false value. Here is an example:

@page
@model Valuable.Pages.EmployeeEvaluationModel

@{
    string conclusion;
    string emplTitle     = "Manager";
    bool   emplIsManager = emplTitle == "Manager";
    
    switch (emplIsManager)
    {
        case true:
            conclusion = "The employee is a manager.";
            break;
        case false:
            conclusion = "The staff member is a regular employee.";
            break;
    }
}

<h3>Employee Evaluation</h3>

<hr />

<p>Employee Title: @emplTitle</p>
<p>Is the employee a manager? @emplIsManager</p>
<p>Conclusion: @conclusion</p>

This would produce:

Employee Evaluation

Employee Title: Manager

Is the employee a manager? True

Conclusion: The employee is a manager.

Switching a Boolean Expression

In the previous example, in the parentheses of switch(), we included a variable that held a Boolean value. As an alternative, you can include a Boolean expression. Here is an example:

@page
@model Valuable.Pages.EmployeeEvaluationModel

@{
    string conclusion;
    string emplTitle     = "Manager";
    
    switch (emplTitle == "Manager")
    {
        case true:
            conclusion = "The employee is a manager.";
            break;
        case false:
            conclusion = "The staff member is a regular employee.";
            break;
    }
}

<h3>Employee Evaluation</h3>

<hr />

<p>Employee Title: @emplTitle</p>
<p>Is the employee a manager? @emplIsManager</p>
<p>Conclusion: @conclusion</p>

Otherwise, all the other comparison operators we studied can also be used. Here is an example:

@page
@model Valuable.Pages.FormattingValuesModel

@{
    double timeWorked = 30.00;
    string strStatement = "";

    switch (timeWorked >= 40.00)
    {
        case true:
            strStatement = "The employee works full-time.";
            break;
        case false:
            strStatement = "The staff member worked part-time.";
            break;
    }
}

<h3>Employee Evaluation</h3>

<hr />

<p>Time Worked: @timeWorked</p>
<p>Conclusion: @strStatement</p>

This would produce:

Employee Evaluation

Time Worked: 30

Conclusion: The staff member worked part-time.

The main idea is to know how to convert an if conditional statement that uses a logical expression.

Practical LearningPractical Learning: Switching a Boolean Expression

  1. Change the Index.cshtml document as follows:
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    @{
        string firstName       = "";
        string lastName        = "";
    
        double hourlySalary    = 0.00;
        double monday          = 0.00;
        double tuesday         = 0.00;
        double wednesday       = 0.00;
        double thursday        = 0.00;
        double friday          = 0.00;
        double timeWorked      = 0.00;
        double netPay          = 0.00;
        
        double regTime         = 0.00;
        double overtime        = 0.00;
        double overPay         = 0.00;
        double regPay          = 0.00;
    
        string strMonday       = "0.00";
        string strTuesday      = "0.00";
        string strWednesday    = "0.00";
        string strThursday     = "0.00";
        string strFriday       = "0.00";
        string strHourlySalary = "0.00";
        string strRegularTime  = "0.00";
        string strOvertime     = "0.00";
        string strRegularPay   = "0.00";
        string strOvertimePay  = "0.00";
        string strNetPay       = "0.00";
    
        if (Request.HasFormContentType)
        {
            firstName    = Request.Form["txtFirstName"];
            lastName     = Request.Form["txtLastName"];
            
            hourlySalary = double.Parse(Request.Form["txtHourlySalary"]);
            monday       = double.Parse(Request.Form["txtMonday"]);
            tuesday      = double.Parse(Request.Form["txtTuesday"]);
            wednesday    = double.Parse(Request.Form["txtWednesday"]);
            thursday     = double.Parse(Request.Form["txtThursday"]);
            friday       = double.Parse(Request.Form["txtFriday"]);
            
            timeWorked = monday + tuesday + wednesday + thursday + friday;
            
            if(timeWorked <= 40.00)
            {
                regTime = timeWorked;
                regPay = hourlySalary * timeWorked;
                overtime = 0.00;
                overPay = 0.00;
            }
            else
            {
                regTime  = 40.00;
                regPay   = hourlySalary * 40.00;
                overtime = timeWorked - 40.00;
                overPay  = hourlySalary * 1.50 * overtime;
            }
            
            netPay          = regPay + overPay;
            
            strMonday       = $"{monday:F}";
            strTuesday      = $"{tuesday:F}";
            strWednesday    = $"{wednesday:F}";
            strThursday     = $"{thursday:F}";
            strFriday       = $"{friday:F}";
            strHourlySalary = $"{hourlySalary:F}";
            strRegularTime  = $"{regTime:F}";
            strOvertime     = $"{overtime:F}";
            strRegularPay   = $"{regPay:F}";
            strOvertimePay  = $"{overPay:F}";
            strNetPay       = $"{netPay:F}";
        }
    }
    
    <h1 class="common-font text-center">Payroll Preparation</h1>       
    
    <hr />
    
    <form name="PayrollEvaluation" method="post" class="common-font">
        <h3 class="text-center">Employee Time Sheet</h3>
        <hr />
        <table style="width: 625px" align="center">
            <tr>
                <td style="width: 125px">@Html.Label("txtFirstName", "First Name:")</td>
                <td>@Html.TextBox("txtFirstName", @firstName, new { @class = "form-control" })</td>
                <td>Last Name:</td>
                <td>@Html.TextBox("txtLastName", @lastName, new { @class = "form-control" })</td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td>Hourly Salary:</td>
                <td>@Html.TextBox("txtHourlySalary", @strHourlySalary, new { @class = "form-control" })</td>
            </tr>
        </table>
        <hr />
        <table style="width: 625px" align="center">
            <tr>
                <td style="width: 125px">&nbsp;</td>
                <td>Monday</td>
                <td>Tuesday</td>
                <td>Wednesday</td>
                <td>Thursday</td>
                <td>Friday</td>
            </tr>
            <tr>
                <td>Time Worked:</td>
                <td>@Html.TextBox("txtMonday", @strMonday, new { @class="form-control" })</td>
                <td>@Html.TextBox("txtTuesday", @strTuesday, new { @class="form-control" })</td>
                <td>@Html.TextBox("txtWednesday", @strWednesday, new { @class="form-control" })</td>
                <td>@Html.TextBox("txtThursday", @strThursday, new { @class="form-control" })</td>
                <td>@Html.TextBox("txtFriday", @strFriday, new { @class="form-control" })</td>
            </tr>
        </table>
        <hr />
        <table style="width: 300px" align="center">
            <tr>
                <td style="width: 50px">&nbsp;</td>
                <td><input type="submit" value="Evaluate Payroll" name="btnEvaluatePayroll" style="width: 150px" /></td>
            </tr>
        </table>
        <hr />
        <table style="width: 625px" align="center">
            <tr style="border-bottom: 1px solid black">
                <td style="width: 225px">&nbsp;</td>
                <td style="width: 225px">Pay Summary</td>
                <td style="text-align: right">Time</td>
                <td style="text-align: right">Pay</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td>&nbsp;</td>
                <td style="text-align: right">Regular:</td>
                <td style="text-align: right">@strRegularTime</td>
                <td style="text-align: right">@strRegularPay</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td>&nbsp;</td>
                <td style="text-align: right">Overtime:</td>
                <td style="text-align: right">@strOvertime</td>
                <td style="text-align: right">@strOvertimePay</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>Net Pay:</td>
                <td style="text-align: right">@strNetPay</td>
            </tr>
        </table>
    </form>
  2. To execute the application to test the form, on the main menu, click Debug -< Start Without Debugging

    Conditional Switches

  3. Set the following values in the text boxes:
    First Name: Patricia
    Last Name: Katts
    Hourly Salary: 27.26
    Monday: 6
    Tuesday: 7.5
    Wednesday: 6.5
    Thursday: 7
    Friday: 8.5

    Conditional Switches

  4. Click the Evaluate Payroll button:

    Conditional Switches

  5. Return to your programming environment
  6. To switch by a Boolean expression, change the code as follows:
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    @{
        . . .
    
        if (Request.HasFormContentType)
        {
            firstName    = Request.Form["txtFirstName"];
            lastName     = Request.Form["txtLastName"];
            
            hourlySalary = double.Parse(Request.Form["txtHourlySalary"]);
            monday       = double.Parse(Request.Form["txtMonday"]);
            tuesday      = double.Parse(Request.Form["txtTuesday"]);
            wednesday    = double.Parse(Request.Form["txtWednesday"]);
            thursday     = double.Parse(Request.Form["txtThursday"]);
            friday       = double.Parse(Request.Form["txtFriday"]);
            
            timeWorked = monday + tuesday + wednesday + thursday + friday;
            
            switch(timeWorked <= 40.00)
            {
                case true:
                    regTime  = timeWorked;
                    regPay   = hourlySalary * timeWorked;
                    overtime = 0.00;
                    overPay  = 0.00;
                    break;
                case false:
                    regTime  = 40.00;
                    regPay   = hourlySalary * 40.00;
                    overtime = timeWorked   - 40.00;
                    overPay  = hourlySalary * 1.50 * overtime;
                    break;
            }
            
            netPay          = regPay + overPay;
            
            strMonday       = $"{monday:F}";
            strTuesday      = $"{tuesday:F}";
            strWednesday    = $"{wednesday:F}";
            strThursday     = $"{thursday:F}";
            strFriday       = $"{friday:F}";
            strHourlySalary = $"{hourlySalary:F}";
            strRegularTime  = $"{regTime:F}";
            strOvertime     = $"{overtime:F}";
            strRegularPay   = $"{regPay:F}";
            strOvertimePay  = $"{overPay:F}";
            strNetPay       = $"{netPay:F}";
        }
    }
  7. To execute and test the form, on the main menu, click Debug and click Start Without Debugging
  8. If the browser displays a Resend button, click it, or refresh the browser
  9. Change the values in the text boxes as follows:
    First Name: Jimmy
    Last Name: Hewes
    Hourly Salary: 21.07
    Monday: 8.5
    Tuesday: 9.5
    Wednesday: 8
    Thursday: 10.5
    Friday: 9
  10. Click the Evaluate Payroll button:

    Conditional Switches

  11. Return to your programming environment

Conditionally Selecting a Case

If you submit a Boolean variable or a logical expression to the parentheses of a switch(), you can process only two value, true and false. As we saw with if else conditional statements, sometimes you have many possibilities you need to consider. To do this in a switch(), you can create different cases and let each consider an outcome. In this case, for each section, type case followed by the desired logical operator and the corresponding value. In the body of the case section, write the code for that comparison. If all cases use the Less Than operator, the case must be listed from the lowest to the highest values. Here are examples:

@page
@model Valuable.Pages.FormattingValuesModel

@{
    int discountRate = 75;
    
    string itemName = "Lime Green Ribbed Asymmetrical One-Shoulder Dress";
    double originalPrice = 124.85;
    int daysInStore = 44;
    
    switch (daysInStore)
    {
        case < 15:
            discountRate = 0;
            break;
        case < 35:
            discountRate = 15;
            break;
        case < 45:
            discountRate = 35;
            break;
        case < 60:
            discountRate = 50;
            break;
    }

    double discountAmount = originalPrice * discountRate / 100;

    string strDiscountAmount = $"{discountAmount:F}";
    string strDiscountedPrice = $"{(originalPrice - discountAmount):F}";
}

<pre>FUN DEPARTMENT STORE
===================================================================
Store Item
-------------------------------------------------------------------
Item Name:        @itemName
Original Price:   @originalPrice
Days in Store:    @daysInStore
-------------------------------------------------------------------
Discount Rate:    @discountRate%
Discount Amount:  @strDiscountAmount
Discounted Price: @strDiscountedPrice
===================================================================</pre>

This would produce:

FUN DEPARTMENT STORE
===================================================================
Store Item
-------------------------------------------------------------------
Item Name:        Lime Green Ribbed Asymmetrical One-Shoulder Dress
Original Price:   124.85
Days in Store:    44
Discount Rate:    35%
Discount Amount:  43.70
Discounted Price: 81.15
===================================================================

If the cases are using a > operator, they must be listed from the highest to the lowest values. Here are examples:

@page
@model Valuable.Pages.FormattingValuesModel

@{
    double counterReadingStart = 1258;
    double counterReadingEnd   = 28836;
    string strAccountType      = "1. Residential Household";

    double first25Therms = 0.00, next15Therms = 0.00, above40Therms = 0.00;

    double gallons = counterReadingEnd - counterReadingStart;
    double HCFTotal = gallons / 748;

    switch(HCFTotal)
    {
        case > 40.00:
            first25Therms = 25.00 * 1.5573;
            next15Therms  = 15.00 * 1.2264;
            above40Therms = (HCFTotal - 40.00) * 0.9624;
            break;
        case > 25.00:
            first25Therms = 25.00 * 1.5573;
            next15Therms  = (HCFTotal - 25.00) * 1.2264;
            above40Therms = 0.00;
            break;
    }

    double waterUsageCharges     = first25Therms + next15Therms + above40Therms;
    double sewerCharges          = waterUsageCharges * 0.252;

    double environmentCharges    = (strAccountType == "1. Residential Household") ? (waterUsageCharges * 0.0025) : (waterUsageCharges * 0.0125);
    double serviceCharges        = (strAccountType == "1. Residential Household") ? (waterUsageCharges * 0.0328)
                                                                                  : (waterUsageCharges * 0.11643);

    double totalCharges          = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges;
    double localTaxes            = (strAccountType == "1. Residential Household") ? (totalCharges * 0.035) : (totalCharges * 0.235);
    double stateTaxes            = (strAccountType == "1. Residential Household") ? (totalCharges * 0.115) : (totalCharges * 0.815);

    string strFirst25Therms      = $"{first25Therms:F}";
    string strNext15Therms       = $"{next15Therms:F}";
    string strAbove40Therms      = $"{above40Therms:F}";
    string strLocalTaxes         = $"{localTaxes:F}";
    string strSateTaxes          = $"{stateTaxes:F}";
    string strTotalCharges       = $"{totalCharges:F}";
    string strSewerCharges       = $"{sewerCharges:F}";
    string strWaterUsageCharges  = $"{waterUsageCharges:F}";
    string strEnvironmentCharges = $"{environmentCharges:F}";
    string strServiceCharges     = $"{serviceCharges:F}";
    string strAmountDue          = $"{(totalCharges + localTaxes + stateTaxes):F}";
}

<pre>Stellar Water Point
======================================================
Types of Accounts
1. Residential Household
2. Laudromat
3. Health Clinic
4. Place of Worship/Youth Center
5. Government Agency
6. Other Business
======================================================
Stellar Water Point - Customer Invoice
======================================================
Meter Reading
------------------------------------------------------
Counter Reading Start:      @counterReadingStart
Counter Reading End:        @counterReadingEnd
Total Gallons Consumed:     @gallons
======================================================
Therms Evaluation
------------------------------------------------------
HCF Total:                  @HCFTotal
First 35 Therms (* 1.5573): @strFirst25Therms
First 20 Therms (* 1.2264): @strNext15Therms
Above 40 Therms (* 0.9624): @strAbove40Therms
------------------------------------------------------
Water Usage Charges:        @strWaterUsageCharges
Sewer Charges:              @strSewerCharges
======================================================
Bill Values
------------------------------------------------------
Environment Charges:        @strEnvironmentCharges
Service Charges:            @strServiceCharges
Total Charges:              @strTotalCharges
Local Taxes:                @strLocalTaxes
State Taxes:                @strSateTaxes
------------------------------------------------------
Amount Due:                 @strAmountDue
======================================================</pre>

This would produce:

Stellar Water Point
======================================================
Types of Accounts
1. Residential Household
2. Laudromat
3. Health Clinic
4. Place of Worship/Youth Center
5. Government Agency
6. Other Business
======================================================
Stellar Water Point - Customer Invoice
======================================================
Meter Reading
------------------------------------------------------
Counter Reading Start:      1258
Counter Reading End:        28836
Total Gallons Consumed:     27578
======================================================
Therms Evaluation
------------------------------------------------------
HCF Total:                  36.86898395721925
First 35 Therms (* 1.5573): 38.93
First 20 Therms (* 1.2264): 14.56
Above 40 Therms (* 0.9624): 0.00
------------------------------------------------------
Water Usage Charges:        53.49
Sewer Charges:              13.48
======================================================
Bill Values
------------------------------------------------------
Environment Charges:        0.13
Service Charges:            1.75
Total Charges:              68.86
Local Taxes:                2.41
State Taxes:                7.92
------------------------------------------------------
Amount Due:                 79.18
======================================================

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2022, FunctionX Friday 21 January 2022 Next