Default Selection

Introduction

Consider the following code:

@page
@model Valuable.Pages.ExerciseModel

@{
    int number = 125;
    string statement = "";

    statement = $"The number is {number}.";
}

<p>@statement</p>

This would produce:

The number is 125.

When you create a switch condition, you are asking the compiler to consider each of the values that can fit the expression in the parentheses of switch(). Normally, you cannot match all the possible or available values. To consider a case that would apply to all possible values that don't fit the expression in the parentheses of switch(), you use a keyword named default. The formula to use the default case is:

switch(expression)
{
    default:
	statement(s);
	break;
}

Start with the default keyword. Like any case selection, the default section must have a body. The body of the default section starts with a colon after the default keyword and ends with a break; line. In the body, you can write any appropriate code you want.

You can create a switch statement that uses only a default case. In that case, the default section is simply a continuation of the previous code. As a result, the above code can be written as follows:

@page
@model Valuable.Pages.ExerciseModel

@{
    int number = 145;
    string statement = "";

    switch (number)
    {
        default:
            statement = $"The number is {number}.";
            break;
    }
}

<p>@statement</p>

In the same way, you can use a Boolean value as condition. Here is an example:

@page
@model Valuable.Pages.FormattingValuesModel

@{
    int number = 85;
    string statement = "";

    if(number is < 100)
        statement = "The number is less than 100.";
}

<pre>Number: @number
@statement</pre>

@{
    number = 125;

    switch(number is > 100)
    {
        default:
            statement = $"The number is greater than 100.";
            break;
    }
}

<pre>Number: @number
@statement</pre>

This would produce:

Number: 85
The number is less than 100.

Number: 125
The number is greater than 100.

Practical LearningPractical Learning: Using Conditional Switching

  1. Start Microsoft Visual Studio and create a new ASP.NET Core Web App named TaxPreparation05. 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

Switching to the default Outcome

We saw that, when all outcomes of an if statement have been considered but none of them fits, you can issue an else statement that would process all conditions that didn't fit any of the if and/or else if situations. Also, the else statement must be the last in an if conditional statement. To address the same type of issue, you can add a default case to a switch statement. The formula to follow would be:

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

The rules of the default case are:

Practical LearningPractical Learning: Switching to the default Outcome

  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)
            {
                default: // "Florida", "Nevada", "Texas", "Washington", "Wyoming"
                    taxRate   = 0.00;
                    break;
    
                case "Tennessee":
                    taxRate   = 1.00;
                    break;
                case "Pennsylvania":
                    taxRate   = 3.07;
                    break;
                case "Indiana":
                    taxRate   = 3.23;
                    break;
                case "Michigan":
                    taxRate   = 4.25;
                    break;
                case "Colorado":
                    taxRate   = 4.63;
                    break;
                case "Illinois":
                    taxRate   = 4.95;
                    break;
                case "Utah":
                    taxRate   = 4.95;
                    break;
                case "Kentucky":
                    taxRate   = 5.00;
                    break;
                case "Massachusetts":
                    taxRate   = 5.00;
                    break;
                case "New Hampshire":
                    taxRate   = 5.00;
                    break;
                case "North Carolina":
                    taxRate   = 5.25;
                    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

    Conditional Switches

  3. In the Select State combo box, select Nevada
  4. In the Gross Salary text box, type 2688.75

    Conditional Switches

  5. Click the Evaluate Taxes button:

    Conditional Switches

  6. In the Select State combo box, select North Carolina
  7. Click the Evaluate Taxes button:

    Conditional Switches

  8. In the Select State combo box, select Washington
  9. Click the Evaluate Taxes button:

    Conditional Switches

  10. Return to your programming environment

Switching and Other Conditional Statements

Nesting a Conditional Statement in a Case

Each case of a switch statement has its own body. In that body, you write any code necessary for the outcome of that case. To process that outcome, you can create one or more conditional statements. This is the same as nesting one or more conditional statements, as we saw when studying conditional conjunctions and disjunctions.

Practical LearningPractical Learning: Nesting a Conditional Statement in a Case

  1. Change the Index.cshtml 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 amountAdded = 0.00;
            double grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
    
            strStateName       = Request.Form["selStates"];
            
            switch (strStateName)
            {
                default: // "Florida", "Nevada", "Texas", "Washington", "Wyoming"
                    taxRate     = 0.00;
                    amountAdded = 0.00;
                    break;
    
                case "Tennessee":
                    taxRate     = 1.00;
                    amountAdded = 0.00;
                    break;
                case "Pennsylvania":
                    taxRate     = 3.07;
                    amountAdded = 0.00;
                    break;
                case "Indiana":
                    taxRate     = 3.23;
                    amountAdded = 0.00;
                    break;
                case "Michigan":
                    taxRate     = 4.25;
                    amountAdded = 0.00;
                    break;
                case "Colorado":
                    taxRate     = 4.63;
                    amountAdded = 0.00;
                    break;
                case "Illinois":
                    taxRate     = 4.95;
                    amountAdded = 0.00;
                    break;
                case "Utah":
                    taxRate     = 4.95;
                    amountAdded = 0.00;
                    break;
                case "Kentucky":
                    taxRate     = 5.00;
                    amountAdded = 0.00;
                    break;
                case "Massachusetts":
                    taxRate     = 5.00;
                    amountAdded = 0.00;
                    break;
                case "New Hampshire":
                    taxRate     = 5.00;
                    amountAdded = 0.00;
                    break;
                case "North Carolina":
                    taxRate     = 5.25;
                    amountAdded = 0.00;
                    break;
                case "Missouri":
                    if( (grossSalary is >= 0.00) && (grossSalary is <= 106) )
                    {
                        amountAdded = 0;
                        taxRate     = 0.00;
                    }
                    else if((grossSalary is > 106) && (grossSalary is <= 1_073))
                    {
                        amountAdded = 0;
                        taxRate     = 1.50;
                    }
                    else if((grossSalary is > 1_073) && (grossSalary is <= 2_146))
                    {
                        amountAdded = 16;
                        taxRate     = 2.00;
                    }
                    else if((grossSalary is is > 2_146) && (grossSalary is is <= 3_219))
                    {
                        amountAdded = 37;
                        taxRate     = 2.50;
                    }
                    else if((grossSalary is > 3_219) && (grossSalary is <= 4_292))
                    {
                        amountAdded = 64;
                        taxRate     = 3.00;
                    }
                    else if((grossSalary is > 4_292) && (grossSalary is <= 5_365))
                    {
                        amountAdded = 96;
                        taxRate     = 3.50;
                    }
                    else if((grossSalary is > 5_365) && (grossSalary is <= 6_438))
                    {
                        amountAdded = 134;
                        taxRate     = 4.00;
                    }
                    else if((grossSalary is > 6_438) && (grossSalary is <= 7_511))
                    {
                        amountAdded = 177;
                        taxRate     = 4.50;
                    }
                    else if((grossSalary is > 7_511) && (grossSalary is <= 8_584))
                    {
                        amountAdded = 225;
                        taxRate     = 5.00;
                    }
                    else // if(grossSalary is > 8_584)
                    {
                        amountAdded = 279;
                        taxRate     = 5.40;
                    }
                    break;
            }
    
            double taxAmount   = amountAdded + (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:</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, on the main menu, click Debug -> Start Without Debugging
  3. If the browser presents a Resend button, click it, or refresh the browser
  4. In the Select a State combo box, select Missouri
  5. Click the Evaluate Taxes button:

    Conditional Switches

  6. In the Select a State combo box, select Missouri again
  7. Change the Gross Salary to 5688.75
  8. Click the Evaluate Taxes button:

    Conditional Switches

  9. Return to your programming environment

Combining Cases

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;.

Practical LearningPractical Learning: Combining Cases

  1. Change the switch statement 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 amountAdded = 0.00;
            double grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
    
            strStateName       = Request.Form["selStates"];
            
            switch (strStateName)
            {
                default: // "Florida", "Nevada", "Texas", "Washington", "Wyoming"
                    taxRate     = 0.00;
                    amountAdded = 0.00;
                    break;
                case "Tennessee":
                    taxRate     = 1.00;
                    amountAdded = 0.00;
                    break;
                case "Pennsylvania":
                    taxRate     = 3.07;
                    amountAdded = 0.00;
                    break;
                case "Illinois":
                case "Utah":
                    taxRate     = 4.95;
                    amountAdded = 0.00;
                    break;
                case "Indiana":
                    taxRate     = 3.23;
                    amountAdded = 0.00;
                    break;
                case "Michigan":
                    taxRate     = 4.25;
                    amountAdded = 0.00;
                    break;
                case "Kentucky":
                case "Massachusetts":
                case "New Hampshire":
                    taxRate     = 5.00;
                    amountAdded = 0.00;
                    break;
                case "Colorado":
                    taxRate     = 4.63;
                    amountAdded = 0.00;
                    break;
                case "North Carolina":
                    taxRate     = 5.25;
                    amountAdded = 0.00;
                    break;
                case "Missouri":
                    . . .
                    break;
            }
    
            double taxAmount   = amountAdded + (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 />
    
    . . .
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. If the browser presents a Resend button, click it, or refresh the browser
  4. In the Select a State combo box, select Kentucky
  5. Click the Evaluate Taxes button:

    Conditional Switches

  6. In the Select a State combo box, select Indiana again
  7. Click the Evaluate Taxes button:

    Conditional Switches

  8. Return to your programming environment

Processing a Switching Return

We have already learned that one way to organize your code is to create functions or methods that each solves a particular problem. One way to make those functions or methods effective is to make them return a value that depends on some conditions. We learned to use if...else conditional statements to perform some validations. The switch statement provides even more controls and options.

Instead of declaring a local variable in the function or method, if the only major operation you are performing on the function/method is to use a switch statement to return a value, you can return the appropriate value in each case. In that case, you don't need a break; statement.

In a function, you can create a conditional switch statement, get a value in each case, assign that value to a variable, and then return that value. Here is an example:

@page
@model PracticalLearning.Pages.Shared.RoadTrafficModel
@{
    string per = IdentifyPeriodOfDay();
}

@functions{
    string IdentifyPeriodOfDay()
    {
        string strPeriod;
        
        /* Periods
         * 1 - Monday-Friday - Night (7PM - 6AM)
         * 2 - Monday-Friday - Morning Rush Hour (6AM - 9AM)
         * 3 - Monday-Friday - Regular Time (9AM - 3PM)
         * 4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM)
         * 5 - Weekend (Saturday-Sunday) and Holidays */
    
        int period = 2;
    
        switch (period)
        {
            case 1:
                strPeriod = "Monday-Friday - Night (7PM - 6AM)";
                break;
            default:
                strPeriod = "Monday-Friday - Regular Time (9AM - 3PM)";
                break;
            case 2:
                strPeriod = "Monday-Friday - Morning Rush Hour (6AM - 9AM)";
                break; 
            case 4:
                strPeriod = "Monday-Friday - Afternoon Rush Hour (3PM - 7PM)";
                break;
            case 5:
                strPeriod = "Weekend (Saturday-Sunday) and Holidays";
                break;
        }
        
        return strPeriod;
    }
}

<pre>=================================================================
Traffic Tickets System
-----------------------------------------------------------------
Period of the day:  @per
=================================================================</pre>

This would produce:

=================================================================
Traffic Tickets System
-----------------------------------------------------------------
Period of the day:  Monday-Friday - Morning Rush Hour (6AM - 9AM)
=================================================================

Practical LearningPractical Learning: Processing a Switching Return

  1. Change the code as follows:
    using static System.Console;
    
    string IdentifyPeriodofDay()
    {
        WriteLine("Periods");
        WriteLine("1 - Monday-Friday - Night (7PM - 6AM)");
        WriteLine("2 - Monday-Friday - Morning Rush Hour (6AM - 9AM)");
        WriteLine("3 - Monday-Friday - Regular Time (9AM - 3PM)");
        WriteLine("4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM)");
        WriteLine("5 - Weekend (Saturday-Sunday) and Holidays");
        WriteLine("----------------------------------------------------------");
        Write("Period of the infraction (1-5): ");
        int period = int.Parse(ReadLine());
        
        switch (period)
        {
            case 1:
                return "Monday-Friday - Night (7PM - 6AM)";   
            case 2:
                return "Monday-Friday - Morning Rush Hour (6AM - 9AM)";
            default: // case 3:
                return "Monday-Friday - Regular Time (9AM - 3PM)";
            case 4:
                return "Monday-Friday - Afternoon Rush Hour (3PM - 7PM)";
            case 5:
                return "Weekend (Saturday-Sunday) and Holidays";    
        }
    }
    
    WriteLine("Traffic Tickets System");
    WriteLine("==========================================================");
    /* Starting here, a police officer, a government clerk, or a designated 
     * user is used an application on a computer. We want the person 
     * to make selections on the application.
     * We want to know the period during which the infraction was committed. */
    strPeriod = IdentifyPeriodofDay();
    WriteLine("==========================================================");
  2. Press Ctrl + S to save
  3. Close Microsoft Visual Studio

Previous Copyright © 2001-2023, FunctionX Thursday 28 October 2021 Next