Conditions for Equality

Introduction

We are now familiar with the ability to find out whether one of two values is higher or lower than the other. In some cases, you want to know whether two values share a similarity.

Practical LearningPractical Learning: Introducing Conditions

  1. Start Microsoft Visual Studio and create a new ASP.NET Core Web App named PayrollPreparation2. Uncheck the Configure for HTTPS check box
  2. In the Solution Explorer, right-click Pages -< Add -> Razor Page...
  3. In the Add New Scaffolded Item dialog box, make sure Razor Page - Empty is selected.
    Click Add
  4. Change the file Name to PayPreparation
  5. Click Create

The Equality Operator ==

To compare two variables for equality, C# provides the == operator. The formula to use it is:

value1 == value2

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. The operation can be illustrated as follows:

Unlike the "Less Than" (<) and the "Greater Than" (>) operations, the equality (==) operator cannot use the is operator.

It is important to make a distinction between the assignment "=" and the logical equality operator "==". The first is used to give a new value to a variable, as in Number = 244. The operand on the left side of = must always be a variable and never a constant. The == operator is never used to assign a value; this would cause an error. The == operator is used only to compare two values. The operands on both sides of == can be variables, constants, or one can be a variable while the other is a constant.

Logical Difference

We already know that the == operator is used to find out if two values are the same. The opposite is to find out whether two values are different. The operator to do this is !=. It can be illustrated as follows:

Flowchart: Not Equal - Inequality - Difference

A typical Boolean expression involves two operands separated by a logical operator. Both operands must be of the same type. These rules apply to the logical difference. It can be used on numbers, strings, etc. If both operands are different, the operation produces a True result. If they are the exact same, the operation produces False.

The != operator can be used the same way as the equality operator (==) as long as you keep in mind that != is the opposite of ==.

Unlike the "Less Than" (<) and the "Greater Than" (>) operations, the logical difference (!=) operator cannot use the is operator.

Less Than Or Equal To: <=

The Equality (==) and the Less Than (<) operations can be combined to compare two values. This allows you to know if two values are the same or if the first value is lower than the second value. The operator used is <= and its syntax is:

value1 is <= value2

The <= operation performs a comparison as any of the last two. If both value1 and value2 hold the same value, the result is True. If the left operand, in this case value1, holds a value lower than the second operand, in this case value2, the result is still True. The <= operation can be illustrated as follows:

Less Than Or Equal

Here is an example that uses the <= operator:

@page
@model Valuable.Pages.FoundationsModel
@using static System.Console

@{
    double originalPrice = 124.50;
    double discountRate = 35.00; // %
    double number_of_days_in_store = 75;

    if (number_of_days_in_store is <= 45)
        discountRate = 25.00;

    double discountAmount = originalPrice * discountRate / 100.00;
    double markedPrice = originalPrice - discountAmount;

    string strOriginalPrice  = $"{originalPrice:N}";
    string strDaysInStore    = $"{number_of_days_in_store}";
    string strDiscountRate   = $"{discountRate:N}";
    string strDiscountAmount = $"{discountAmount:N}";
    string strMarkedPrice    = $"{markedPrice:N}";
}

<pre>Fun Department Store");
----------------------------------
Original Price:  @strOriginalPrice
Days in Store:   @number_of_days_in_store
Discount Rate:   @discountRate
Discount Amount: @discountAmount
Marked Price:    @markedPrice</pre>

@{
    number_of_days_in_store = 22;
    
    if (number_of_days_in_store is <= 45)
        discountRate = 25.00;
    
    discountAmount = originalPrice * discountRate / 100.00;
    markedPrice = originalPrice - discountAmount;
}

<pre>Fun Department Store");
----------------------------------
Original Price:  @strOriginalPrice
Days in Store:   @number_of_days_in_store
Discount Rate:   @discountRate
Discount Amount: @discountAmount
Marked Price:    @markedPrice</pre>

This would produce:

Fun Department Store
----------------------------------
Original Price:  124.50
Days in Store:   75
Discount Rate:   35
Discount Amount: 43.575
Marked Price:    80.925

Fun Department Store
----------------------------------
Original Price:  124.50
Days in Store:   22
Discount Rate:   25
Discount Amount: 31.125
Marked Price:    93.375

ApplicationPractical Learning: Comparing for a Lesser Value

  1. Change the Razor Page as follows:
    @page
    @model PayrollPreparation2.Pages.PayPreparationModel
    @{
        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;
            
            regTime      = 40.00;
            regPay       = hourlySalary * 40.00;
            overtime     = timeWorked - 40.00;
            overPay      = hourlySalary * 1.50 * overtime;
            
            if( timeWorked is <= 40.00)
            {
                regTime  = timeWorked;
                regPay   = hourlySalary * timeWorked;
                overtime = 0.00;
                overPay  = 0.00;
            }
            
            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 style="text-align: center">Payroll Preparation</h1>       
    
    <hr />
    
    <form name="PayrollEvaluation" method="post">
        <h3 style="text-align: center">Employee Information</h3>
        <hr />
        <table style="width: 625px" align="center">
            <tr>
                <td style="width: 125px">First Name:</td>
                <td><input type="text" style="width: 100px" id="txtFirstName" name="txtFirstName" value="@firstName" /></td>
                <td>Last Name:</td>
                <td><input type="text" style="width: 100px" id="txtLastName" name="txtLastName" value="@lastName" /></td>
                <td>Hourly Salary:</td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtHourlySalary" name="txtHourlySalary" value="@strHourlySalary" /></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><input type="text" style="width: 100px; text-align: right" id="txtMonday" name="txtMonday" value="@strMonday" /></td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtTuesday" name="txtTuesday" value="@strTuesday" /></td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtWednesday" name="txtWednesday" value="@strWednesday" /></td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtThursday" name="txtThursday" value="@strThursday" /></td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtFriday" name="txtFriday" value="@strFriday" /></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, press Ctrl + F5
  3. In the browser, click the right side of the address, type /PayPreparation and press Enter

    Conditional Statements

  4. Type the following values like in the text boxes:
    First Name:    Anne
    Last Name:     Murdock
    Hourly Salary: 19.27
    Monday:        7.5
    Tuesday:       8
    Wednesday:     6.5
    Thursday:      8
    Friday:        6.5

    Conditional Statements

  5. Click the Evaluate Payroll button

    Conditional Statements

  6. Change the values as follows and click the button:
    First Name:    Emilio
    Last Name:     Cordova
    Hourly Salary: 22.16
    Monday:        9.5
    Tuesday:       8
    Wednesday:     7.5
    Thursday:      10.5
    Friday:        8

    Conditional Statements

  7. Close the browser and return to your programming environment
  8. Start a new ASP.NET Core Web App named StraightLineMethod2. Uncheck the Configure for HTTPS check box
  9. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  10. In the Add New Scaffolded Item dialog box, make sure Razor Page - Empty is selected.
    Click Add
  11. Change the file Name to Depreciation
  12. Click Create
  13. Change the document as follows:
    @page
    @model StraightLineMethod2.Pages.DepreciationModel
    @{
        int    year = 0;
        int    estimatedLife = 0;
        double machineCost   = 0.00;
        double salvageValue  = 0.00;
        double depreciationRate = 0.00;
        double yearlyDepreciation = 0.00;
        string strDepreciation12 = "0.00";
    
        double bookValueYear0  = 0.00;
        double bookValueYear1  = 0.00;
        double bookValueYear2  = 0.00;
        double bookValueYear3  = 0.00;
        double bookValueYear4  = 0.00;
        double bookValueYear5  = 0.00;
        double bookValueYear6  = 0.00;
        double bookValueYear7  = 0.00;
        double bookValueYear8  = 0.00;
        double bookValueYear9  = 0.00;
        double bookValueYear10 = 0.00;
    
        string strBookValueYear0  = "0.00";
        string strBookValueYear1  = "0.00";
        string strBookValueYear2  = "0.00";
        string strBookValueYear3  = "0.00";
        string strBookValueYear4  = "0.00";
        string strBookValueYear5  = "0.00";
        string strBookValueYear6  = "0.00";
        string strBookValueYear7  = "0.00";
        string strBookValueYear8  = "0.00";
        string strBookValueYear9  = "0.00";
        string strBookValueYear10 = "0.00";
    
        string strAccumulatedDepreciation1  = "0.00";
        string strAccumulatedDepreciation2  = "0.00";
        string strAccumulatedDepreciation3  = "0.00";
        string strAccumulatedDepreciation4  = "0.00";
        string strAccumulatedDepreciation5  = "0.00";
        string strAccumulatedDepreciation6  = "0.00";
        string strAccumulatedDepreciation7  = "0.00";
        string strAccumulatedDepreciation8  = "0.00";
        string strAccumulatedDepreciation9  = "0.00";
        string strAccumulatedDepreciation10 = "0.00";
    
        string strYearlyDepreciation        = "0.00";
    
        if (Request.HasFormContentType)
        {
            machineCost   = double.Parse(Request.Form["txtMachineCost"]);
            salvageValue  = double.Parse(Request.Form["txtSalvageValue"]);
            estimatedLife = int.Parse(Request.Form["txtEstimatedLife"]);
    
            depreciationRate   = 100 / estimatedLife;
            yearlyDepreciation = (machineCost - salvageValue) / estimatedLife;
            strDepreciation12 = $"{(yearlyDepreciation / 12):n}";
    
            strYearlyDepreciation = $"{yearlyDepreciation:f}";
    
            bookValueYear0  = machineCost - (yearlyDepreciation *  0);
            bookValueYear1  = machineCost - (yearlyDepreciation *  1);
            bookValueYear2  = machineCost - (yearlyDepreciation *  2);
            bookValueYear3  = machineCost - (yearlyDepreciation *  3);
            bookValueYear4  = machineCost - (yearlyDepreciation *  4);
            bookValueYear5  = machineCost - (yearlyDepreciation *  5);
            bookValueYear6  = machineCost - (yearlyDepreciation *  6);
            bookValueYear7  = machineCost - (yearlyDepreciation *  7);
            bookValueYear8  = machineCost - (yearlyDepreciation *  8);
            bookValueYear9  = machineCost - (yearlyDepreciation *  9);
            bookValueYear10 = machineCost - (yearlyDepreciation * 10);
    
            strBookValueYear0  = $"{bookValueYear0:F}";
            strBookValueYear1  = $"{bookValueYear1:F}";
            strBookValueYear2  = $"{bookValueYear2:F}";
            strBookValueYear3  = $"{bookValueYear3:F}";
            strBookValueYear4  = $"{bookValueYear4:F}";
            strBookValueYear5  = $"{bookValueYear5:F}";
            strBookValueYear6  = $"{bookValueYear6:F}";
            strBookValueYear7  = $"{bookValueYear7:F}";
            strBookValueYear8  = $"{bookValueYear8:F}";
            strBookValueYear9  = $"{bookValueYear9:F}";
            strBookValueYear10 = $"{bookValueYear10:F}";
            
            strAccumulatedDepreciation1  = $"{yearlyDepreciation *  1:F}";
            strAccumulatedDepreciation2  = $"{yearlyDepreciation *  2:F}";
            strAccumulatedDepreciation3  = $"{yearlyDepreciation *  3:F}";
            strAccumulatedDepreciation4  = $"{yearlyDepreciation *  4:F}";
            strAccumulatedDepreciation5  = $"{yearlyDepreciation *  5:F}";
            strAccumulatedDepreciation6  = $"{yearlyDepreciation *  6:F}";
            strAccumulatedDepreciation7  = $"{yearlyDepreciation *  7:F}";
            strAccumulatedDepreciation8  = $"{yearlyDepreciation *  8:F}";
            strAccumulatedDepreciation9  = $"{yearlyDepreciation *  9:F}";
            strAccumulatedDepreciation10 = $"{yearlyDepreciation * 10:F}";
        }
    }
    
    <h1 style="text-align: center">Machine Depreciation Evaluation - Straight-Line Method</h1>
    
    <hr />
    
    <form name="PayrollEvaluation" method="post">
        <table style="width: 625px" align="center">
            <tr>
                <td style="width: 125px">Machine Cost:</td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtMachineCost" name="txtMachineCost" value="@machineCost" /></td>
            </tr>
            <tr>
                <td>Salvage Value:</td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtSalvageValue" name="txtSalvageValue" value="@salvageValue" /></td>
            </tr>
            <tr>
                <td>Estimated Life:</td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtEstimatedLife" name="txtEstimatedLife" value="@estimatedLife" /> years</td>
            </tr>
        </table>
    
        <hr />
        
        <table style="width: 300px" align="center">
            <tr>
                <td style="width: 50px">&nbsp;</td>
                <td><input type="submit" value="Calculate Depreciation" name="btnCalculate" style="width: 200px" /></td>
            </tr>
        </table>
    </form>
    
    <hr />
    
        <table style="width: 625px" align="center">
            <tr>
                <td style="width: 200px">Depreciation Rate:</td>
                <td>@depreciationRate</td>
            </tr>
            <tr>
                <td>Yearly Depreciation:</td>
                <td>@strYearlyDepreciation /year</td>
            </tr>
            <tr>
                <td>Monthly Depreciation:</td>
                <td>@strDepreciation12 /month</td>
            </tr>
        </table>
        <hr />
        <table style="width: 625px" align="center" border="3">
            <tr style="border-bottom: 1px solid black">
                <td>Year</td>
                <td style="text-align: center">Yearly Depreciation</td>
                <td>Book Value</td>
                <td>Accumulated Depreciation</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@year</td>
                <td></td>
                <td>@strBookValueYear0</td>
                <td></td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 1)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear1</td>
                <td style="text-align: center">@strAccumulatedDepreciation1</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 2)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear2</td>
                <td style="text-align: center">@strAccumulatedDepreciation2</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 3)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear3</td>
                <td style="text-align: center">@strAccumulatedDepreciation3</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 4)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear4</td>
                <td style="text-align: center">@strAccumulatedDepreciation4</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 5)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear5</td>
                <td style="text-align: center">@strAccumulatedDepreciation5</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 6)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear6</td>
                <td style="text-align: center">@strAccumulatedDepreciation6</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 7)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear7</td>
                <td style="text-align: center">@strAccumulatedDepreciation7</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 8)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear8</td>
                <td style="text-align: center">@strAccumulatedDepreciation8</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 9)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear9</td>
                <td style="text-align: center">@strAccumulatedDepreciation9</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 10)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear10</td>
                <td style="text-align: center">@strAccumulatedDepreciation10</td>
            </tr>
        </table>
  14. To execute, on the main menu, click Debug -> Start Without Debugging
  15. In the browser, click the right side of the address, type /Depreciation and press Enter

    Conditional Statements

  16. Click the Machine Cost text box and type 8568.95
  17. Click the Salvage Value text box and type 550
  18. Click the Estimated Life text box and type 5

    Conditional Statements

  19. Click the button on the form

    Conditional Statements

  20. Change the Machine Cost to 15888.65
  21. Change the Salvage Value to 1250
  22. Change the Estimated Life to 10 and click the button:

    Conditional Statements

  23. Return to your programming environment

A Value Greater Than or Equal to Another: >=

The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. The formula it follows is:

value1 is >= value2

The comparison is performed on both operands: value1 and value2:

This operation can be illustrated as follows:

Flowchart: Greater Than Or Equal To

Here is an example that uses the >= operator:

@page
@model Valuable.Pages.FoundationsModel

@{
    double consumption = 0.74;
    double pricePerCCF = 0.00;
    
    if (consumption is >= 0.50)
        pricePerCCF = 35.00;
    
    double monthlyCharges = consumption * pricePerCCF;
}

<pre>Gas Utility Company
-----------------------------
Gas Consumption: @consumption
Price Per CCF:   @pricePerCCF
Monthly Charges: @monthlyCharges</pre>

This would produce:

Gas Utility Company
---------------------------------
Gas Consumption:  0.74
Price Per CCF:    35.0
Monthly Charges:  25.9

Practical LearningPractical Learning: Comparing for a Value Greater Than or Equal to Another

  1. Change the document as follows:
    @page
    @model StraightLineMethod2.Pages.DepreciationModel
    @{
        int    year = 0;
        int    estimatedLife = 0;
        double machineCost   = 0.00;
        double salvageValue  = 0.00;
        double depreciationRate = 0.00;
        double yearlyDepreciation = 0.00;
        string strDepreciation12 = "0.00";
    
        double bookValueYear0  = 0.00;
        double bookValueYear1  = 0.00;
        double bookValueYear2  = 0.00;
        double bookValueYear3  = 0.00;
        double bookValueYear4  = 0.00;
        double bookValueYear5  = 0.00;
        double bookValueYear6  = 0.00;
        double bookValueYear7  = 0.00;
        double bookValueYear8  = 0.00;
        double bookValueYear9  = 0.00;
        double bookValueYear10 = 0.00;
    
        string strBookValueYear0  = "0.00";
        string strBookValueYear1  = "0.00";
        string strBookValueYear2  = "0.00";
        string strBookValueYear3  = "0.00";
        string strBookValueYear4  = "0.00";
        string strBookValueYear5  = "0.00";
        string strBookValueYear6  = "0.00";
        string strBookValueYear7  = "0.00";
        string strBookValueYear8  = "0.00";
        string strBookValueYear9  = "0.00";
        string strBookValueYear10 = "0.00";
    
        string strAccumulatedDepreciation1  = "0.00";
        string strAccumulatedDepreciation2  = "0.00";
        string strAccumulatedDepreciation3  = "0.00";
        string strAccumulatedDepreciation4  = "0.00";
        string strAccumulatedDepreciation5  = "0.00";
        string strAccumulatedDepreciation6  = "0.00";
        string strAccumulatedDepreciation7  = "0.00";
        string strAccumulatedDepreciation8  = "0.00";
        string strAccumulatedDepreciation9  = "0.00";
        string strAccumulatedDepreciation10 = "0.00";
    
        string strYearlyDepreciation        = "0.00";
    
        if (Request.HasFormContentType)
        {
            machineCost   = double.Parse(Request.Form["txtMachineCost"]);
            salvageValue  = double.Parse(Request.Form["txtSalvageValue"]);
            estimatedLife = int.Parse(Request.Form["txtEstimatedLife"]);
    
            depreciationRate   = 100 / estimatedLife;
            yearlyDepreciation = (machineCost - salvageValue) / estimatedLife;
            strDepreciation12 = $"{(yearlyDepreciation / 12):n}";
    
            strYearlyDepreciation = $"{yearlyDepreciation:f}";
    
            bookValueYear0  = machineCost - (yearlyDepreciation *  0);
            bookValueYear1  = machineCost - (yearlyDepreciation *  1);
            bookValueYear2  = machineCost - (yearlyDepreciation *  2);
            bookValueYear3  = machineCost - (yearlyDepreciation *  3);
            bookValueYear4  = machineCost - (yearlyDepreciation *  4);
            bookValueYear5  = machineCost - (yearlyDepreciation *  5);
            bookValueYear6  = machineCost - (yearlyDepreciation *  6);
            bookValueYear7  = machineCost - (yearlyDepreciation *  7);
            bookValueYear8  = machineCost - (yearlyDepreciation *  8);
            bookValueYear9  = machineCost - (yearlyDepreciation *  9);
            bookValueYear10 = machineCost - (yearlyDepreciation * 10);
    
            strBookValueYear0  = $"{bookValueYear0:F}";
            strBookValueYear1  = $"{bookValueYear1:F}";
            strBookValueYear2  = $"{bookValueYear2:F}";
            strBookValueYear3  = $"{bookValueYear3:F}";
            strBookValueYear4  = $"{bookValueYear4:F}";
            strBookValueYear5  = $"{bookValueYear5:F}";
            strBookValueYear6  = $"{bookValueYear6:F}";
            strBookValueYear7  = $"{bookValueYear7:F}";
            strBookValueYear8  = $"{bookValueYear8:F}";
            strBookValueYear9  = $"{bookValueYear9:F}";
            strBookValueYear10 = $"{bookValueYear10:F}";
            
            strAccumulatedDepreciation1  = $"{yearlyDepreciation *  1:F}";
            strAccumulatedDepreciation2  = $"{yearlyDepreciation *  2:F}";
            strAccumulatedDepreciation3  = $"{yearlyDepreciation *  3:F}";
            strAccumulatedDepreciation4  = $"{yearlyDepreciation *  4:F}";
            strAccumulatedDepreciation5  = $"{yearlyDepreciation *  5:F}";
            strAccumulatedDepreciation6  = $"{yearlyDepreciation *  6:F}";
            strAccumulatedDepreciation7  = $"{yearlyDepreciation *  7:F}";
            strAccumulatedDepreciation8  = $"{yearlyDepreciation *  8:F}";
            strAccumulatedDepreciation9  = $"{yearlyDepreciation *  9:F}";
            strAccumulatedDepreciation10 = $"{yearlyDepreciation * 10:F}";
        }
    }
    
    <h1 style="text-align: center">Machine Depreciation Evaluation - Straight-Line Method</h1>
    
    <hr />
    
    <form name="PayrollEvaluation" method="post">
        <table style="width: 625px" align="center">
            <tr>
                <td style="width: 125px">Machine Cost:</td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtMachineCost" name="txtMachineCost" value="@machineCost" /></td>
            </tr>
            <tr>
                <td>Salvage Value:</td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtSalvageValue" name="txtSalvageValue" value="@salvageValue" /></td>
            </tr>
            <tr>
                <td>Estimated Life:</td>
                <td><input type="text" style="width: 100px; text-align: right" id="txtEstimatedLife" name="txtEstimatedLife" value="@estimatedLife" /> years</td>
            </tr>
        </table>
    
        <hr />
        
        <table style="width: 300px" align="center">
            <tr>
                <td style="width: 50px">&nbsp;</td>
                <td><input type="submit" value="Calculate Depreciation" name="btnCalculate" style="width: 200px" /></td>
            </tr>
        </table>
    </form>
    
    <hr />
    
        <table style="width: 625px" align="center">
            <tr>
                <td style="width: 200px">Depreciation Rate:</td>
                <td>@depreciationRate</td>
            </tr>
            <tr>
                <td>Yearly Depreciation:</td>
                <td>@strYearlyDepreciation /year</td>
            </tr>
            <tr>
                <td>Monthly Depreciation:</td>
                <td>@strDepreciation12 /month</td>
            </tr>
        </table>
        <hr />
        <table style="width: 625px" align="center" border="3">
            <tr style="border-bottom: 1px solid black">
                <td>Year</td>
                <td style="text-align: center">Yearly Depreciation</td>
                <td>Book Value</td>
                <td>Accumulated Depreciation</td>
            </tr>
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@year</td>
                <td></td>
                <td>@strBookValueYear0</td>
                <td></td>
            </tr>
    @if (bookValueYear1 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 1)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear1</td>
                <td style="text-align: center">@strAccumulatedDepreciation1</td>
            </tr>
    }
    @if (bookValueYear2 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 2)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear2</td>
                <td style="text-align: center">@strAccumulatedDepreciation2</td>
            </tr>
    }
    @if (bookValueYear3 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 3)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear3</td>
                <td style="text-align: center">@strAccumulatedDepreciation3</td>
            </tr>
    }
    @if (bookValueYear4 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 4)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear4</td>
                <td style="text-align: center">@strAccumulatedDepreciation4</td>
            </tr>
    }
    @if (bookValueYear5 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 5)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear5</td>
                <td style="text-align: center">@strAccumulatedDepreciation5</td>
            </tr>
    }
    @if (bookValueYear6 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 6)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear6</td>
                <td style="text-align: center">@strAccumulatedDepreciation6</td>
            </tr>
    }
    @if (bookValueYear7 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 7)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear7</td>
                <td style="text-align: center">@strAccumulatedDepreciation7</td>
            </tr>
    }
    @if (bookValueYear8 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 8)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear8</td>
                <td style="text-align: center">@strAccumulatedDepreciation8</td>
            </tr>
    }
    @if (bookValueYear9 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 9)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear9</td>
                <td style="text-align: center">@strAccumulatedDepreciation9</td>
            </tr>
    }
    @if (bookValueYear10 is >= 0)
    {
            <tr style="border-bottom: 1px solid black">
                <td style="text-align: center">@(year + 10)</td>
                <td style="text-align: center">@strYearlyDepreciation</td>
                <td>@strBookValueYear10</td>
                <td style="text-align: center">@strAccumulatedDepreciation10</td>
            </tr>
    }
        </table>
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. Change the value in the Machine Cost text box to 8568.95
  4. Change the value in the Salvage Value text box to 550 and press Enter
  5. Change the value in the Estimated Life text box to 5 and click the button

    Conditional Statements

  6. Return to your programming environment

Options on IF Conditions

if a Condition is True/False

One way to formulate a conditional statement is to find out whether a situation is true or false. In this case, one of the operands must be a Boolean value as true or false. The other operand can be a Boolean variable. Here is an example:

bool employeeIsFullTime = false;;

if( false == employeeIsFullTime)
{
            
}

One of the operands can also be an expression that holds a Boolean value.

Imagine that you want to evaluate the condition as true. Here is an example:

bool employeeIsFullTime = true;

if( employeeIsFullTime == true)
{
            
}

If a Boolean variable (currently) holds a true value (at the time you are trying to access it), when you are evaluating the expression as being true, you can omit the == true or the true == expression in your statement. Therefore, the above expression can be written as follows:

bool employeeIsFullTime = true;

. . . No Change

if( employeeIsFullTime)
{

}

This would produce the same result as previously.

Negating a Condition

On the other hand, if you have a logical expression or value, to let you get its logical opposite, the C# language provides the logical NOT operator represented by !. The formula to use it is:

!variable-or-expression

Actually there are various ways the logical NOT operator is used. The classic way is to check the state of a variable. To nullify a variable, you can write the exclamation point to its left. Here is an example:

bool employed = true;

bool validation = !employed;

When a variable has been "negated", its logical value changes. If the logical value was true, it would be changed to false. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it.

If There Is No Need

We saw that the <, the <=, the >, and the >= operators can be preceded by the is keyword. To make your code a little simpler, you can omit the is keyword.

Otherwise, to make your code easy to read, you can use the is keyword.

Practical LearningPractical Learning: Creating Conditional Statements

  1. Start a New Project as an ASP.NET Core Web App named FunDepartmentStore2 unchecking Configure for HTTPS
  2. In the Solution Explorer, right-click Pages -> Add -> Razor Page...
  3. Add the central list of the Add New Scaffolded Item dialog box, make sure Razor Page - Empty is selected.
    Click Add
  4. Change the file Name to StoreInventory
  5. Click Add
  6. Change the document as follows:
    @page
    @model Valuable.Pages.FoundationsModel
    @{
        string itemName = "Nothing";
        int discountRate = 0;
        int    daysInStore = 0;
        double originalPrice = 0.00;
        double discountedPrice = 0.00;
        double discountAmount = 0.00;
        string strDiscountAmount = "0.00";
        string strDiscountedPrice = "0.00";
    
        if (Request.HasFormContentType)
        {
            itemName = Request.Form["txtItemName"];
            originalPrice = double.Parse(Request.Form["txtOriginalPrice"]);
            daysInStore = int.Parse(Request.Form["txtDaysInStore"]);
        
            if(daysInStore < 60)
                discountRate = 50;
            if(daysInStore < 45)
                discountRate = 35;
            if(daysInStore < 35)
                discountRate = 15;
            if(daysInStore < 15)
                discountRate = 0;
    
            discountAmount  = originalPrice * discountRate / 100;
            discountedPrice = originalPrice - discountAmount;
    
            strDiscountAmount = $"{discountAmount:F}";
            strDiscountedPrice = $"{discountedPrice:F}";
        }
    }
    
    <h2 style="text-align: center">FUN DEPARTMENT STORE</h2>
    
    <form method="post" name="frmDepartmentStore">
        <table style="width: 500px" align="center">
            <tr>
                <td style="width: 150px">Item Name:</td>
                <td><input type="text" id="txtItemName" name="txtItemName" value="@itemName" style="width: 345px" /></td>
            </tr>
            <tr>
                <td>Original Price:</td>
                <td><input type="text" id="txtOriginalPrice" name="txtOriginalPrice" value="@originalPrice" style="width: 100px" /></td>
            </tr>
            <tr>
                <td>Days in Store:</td>
                <td><input type="text" id="txtDaysInStore" name="txtDaysInStore" value="@daysInStore" style="width: 100px" /></td>
            </tr>
        </table>
    
        <table style="width: 300px" align="center">
            <tr>
                <td style="width: 50px">&nbsp;</td>
                <td><input type="submit" value="Add" name="btnCalculate" style="width: 150px" /></td>
            </tr>
        </table>
    
        <table style="width: 500px" align="center">
            <tr>
                <td style="width: 150px">Discount Rate:</td>
                <td><input type="text" id="txtDiscountRate" name="txtDiscountRate" value="@discountRate" style="width: 100px" /> %</td>
            </tr>
            <tr>
                <td>Discount Amount:</td>
                <td><input type="text" id="txtDiscountAmount" name="txtDiscountAmount" value="@strDiscountAmount" style="width: 100px" /></td>
            </tr>
            <tr>
                <td>Discounted Price:</td>
                <td><input type="text" id="txtDiscountedPrice" name="txtDiscountedPrice" value="@strDiscountedPrice" style="width: 100px" /></td>
            </tr>
        </table>
    </form>
  7. To execute, on the main menu, click Debug -> Start Without Debugging
  8. In the browser, click the right side of the adresss, type /StoreInventory and press Enter:

    Introduction to Conditional Statements

  9. Click the Item Name text box and type Women's Ticker Ankle Boot
  10. Click the Original Price text box and type 134.85
  11. Click the Days in Store text box and type 28

    Introduction to Conditional Statements

  12. Click the Add button

    Converting a Value to Double

  13. Close the browser and return to your programming environment

Negating IS NOT Bad

Once again, we saw that the <, the <=, the >, and the >= operators can be preceded by the is keyword. Here is an example that uses the >= operator:

@page
@model Valuable.Pages.FoundationsModel
@{
    int level = 0;
    string conclusion = "Failed or no Clearance";

    if (Request.HasFormContentType)
    {
        level = int.Parse(Request.Form["txtSecurityClearance"]);
        
        if(level is >= 3)
            conclusion = "Welcome on board";
    }
}

<h2 style="text-align: center">SECURITY CLEARANCE</h2>

<form method="post" name="frmSecurityClearance">
    <p>To grant you this job, we need to ask a few questions.</p>
    <p>Levels of Security Clearance:</p>
    <p>0 - Unknown or None</p>
    <p>1 - Non-Sensitive</p>
    <p>2. National Security - Non-Critical Sensitive</p>
    <p>3. National Security - Critical Sensitive</p>
    <p>4. National Security - Special Sensitive</p>
    <p>Type the numeric level: <input type="text" style="width: 50px" id="txtSecurityClearance" name="txtSecurityClearance" value="@level" /></p>
    <p><input type="submit" value="Validate" name="btnValidate" style="width: 150px" /></p>
</form>

<p>@conclusion.</p>

Here is an example of running the program:

Conditional Statement: is

Conditional Statement: is

To get the opposite result of those operator, you can use an operator named not. The expression to use is is not. Here is an example:

@page
@model Valuable.Pages.FoundationsModel
@{
    int level = 0;
    string conclusion = "You passed the Security Clearance. Welcome on board";

    if (Request.HasFormContentType)
    {
        level = int.Parse(Request.Form["txtSecurityClearance"]);
        
        if(level is not >= 3)
            conclusion = "You failed the Security Clearance or the Clearance was not conclusive.";
    }
}

<h2 style="text-align: center">SECURITY CLEARANCE</h2>

<form method="post" name="frmSecurityClearance">
    <p>To grant you this job, we need to ask a few questions.</p>
    <p>Levels of Security Clearance:</p>
    <p>0 - Unknown or None</p>
    <p>1 - Non-Sensitive</p>
    <p>2. National Security - Non-Critical Sensitive</p>
    <p>3. National Security - Critical Sensitive</p>
    <p>4. National Security - Special Sensitive</p>
    <p>Type the numeric level: <input type="text" style="width: 50px" id="txtSecurityClearance" name="txtSecurityClearance" value="@level" /></p>
    <p><input type="submit" value="Validate" name="btnValidate" style="width: 150px" /></p>
</form>

<p>@conclusion.</p>

Conditional Statement: is not

Here is an example of running the program:

Conditional Statement: is not

A Summary of Logical Operators

As you might have found out, every logical operator has an opposite. They can be resumed as follows:

Operator Meaning Example Opposite
== Equality to a == b !=
!= Not equal to 12 != 7 ==
< is < Less than 25 < 84 >=
<= is <= Less than or equal to Cab <= Tab >
> is > Greater than 248 > 55 <=
>= is >= Greater than or equal to Val1 >= Val2 <

Previous Copyright © 2001-2023, FunctionX Wednesday 27 October 2021 Next