Introduction to Conditional Statements
Introduction to Conditional Statements
What Else?
Introduction
In the previous lessons, we were introduced to logical operators. We also got introduced to conditional statements with the if operator. There are many more operators available to perform logical comparisons.
Practical Learning: Introducing Conditions
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
.btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus {
box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb;
}
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px;
}
.w100 { width: 100px; }
.w150 { width: 150px; }
.w200 { width: 200px; }
.w250 { width: 250px; }
.w700 { width: 700px; }
.common-font { font-family: Georgia, Garamond, 'Times New Roman', serif }
@page @model IndexModel @{ string accountType = ""; double counterReadingEnd = 0.00, counterReadingStart = 0.00, gallons = 0.00; double localTaxes = 0.00, stateTaxes = 0.00; double serviceCharges = 0.00, environmentCharges = 0.00; double first25Therms = 0.00, next15Therms = 0.00, above40Therms = 0.00; double waterUsageCharges = 0.00, sewerCharges = 0.00; double HCFTotal = 0.00, totalCharges = 0.00; string strHCFTotal = "0.00"; string strWaterUsageCharges = "0.00", strSewerCharges = "0.00"; string strServiceCharges = "0.00", strEnvironmentCharges = "0.00"; string strTotalCharges = "0.00", strAmountDue = "0.00"; string strStateTaxes = "0.00", strLocalTaxes = "0.00"; string strFirst25Therms = "0.00", strNext15Therms = "0.00", strAbove40Therms = "0.00"; if (Request.HasFormContentType) { accountType = Request.Form["AccountsTypes"]; counterReadingStart = double.Parse(Request.Form["txtCounterReadingStart"]); counterReadingEnd = double.Parse(Request.Form["txtCounterReadingEnd"]); gallons = counterReadingEnd - counterReadingStart; HCFTotal = gallons / 748; first25Therms = 25.00 * 1.5573; next15Therms = 15.00 * 1.2264; above40Therms = (HCFTotal - 40.00) * 0.9624; waterUsageCharges = first25Therms + next15Therms + above40Therms; sewerCharges = waterUsageCharges * 0.252; environmentCharges = waterUsageCharges * 0.0025; serviceCharges = waterUsageCharges * 0.0328; totalCharges = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges; localTaxes = totalCharges * 0.005259; stateTaxes = totalCharges * 0.002262; strFirst25Therms = $"{first25Therms:F}"; strNext15Therms = $"{next15Therms:F}"; strAbove40Therms = $"{above40Therms:F}"; strHCFTotal = $"{HCFTotal:F}"; strWaterUsageCharges = $"{waterUsageCharges:F}"; strSewerCharges = $"{sewerCharges:F}"; strServiceCharges = $"{serviceCharges:F}"; strEnvironmentCharges = $"{environmentCharges:F}"; strTotalCharges = $"{totalCharges:F}"; strStateTaxes = $"{stateTaxes:F}"; strLocalTaxes = $"{localTaxes:F}"; strAmountDue = $"{(totalCharges + localTaxes + stateTaxes):F}"; } } <div class="common-font"> <h2 class="text-center fw-bold">Stellar Water Point - Customer Invoice</h2> <form method="post" name="frmSecurityClearance"> <table class="w700" align="center"> <tr> <td class="w200 fw-bold">Select Type of Account:</td> <td> <select id="AccountsTypes"> <option value="other">0. Other</option> <option value="residential">1. Residential Household</option> <option value="npo">2. Social/Non-Profit Organization</option> <option value="intensive">3. Water Intensive Business (Laudromat, etc)</option> <option value="general">4. Government/General Business</option> </select> </td> </tr> </table> <hr /> <h3 class="fw-bold">Meter Reading</h3> <hr /> <table class="w700" align="center"> <tr> <td class="w200 fw-bold">Counter Reading Start:</td> <td> <input type="text" class="w100" id="txtCounterReadingStart" name="txtCounterReadingStart" value="@counterReadingStart" /> </td> <td class="w200 fw-bold">Counter Reading End:</td> <td> <input type="text" class="w100" id="txtCounterReadingEnd" name="txtCounterReadingEnd" value="@counterReadingEnd" /> </td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Prepare Water Bill" name="btnPrepare" class="w150" /></td> </tr> </table> <hr /> <table class="w700" align="center"> <tr> <td class="w250 fw-bold">Total Gallons Consumed:</td> <td style="width: 105px">@gallons</td> <td class="fw-bold">HCF Total:</td> <td>@strHCFTotal</td> </tr> </table> <hr /> <h3 class="fw-bold">Therms Evaluation</h3> <hr /> <table class="w700" align="center"> <tr> <td><span class="fw-bold">First Tier Therms:</span> @strFirst25Therms</td> <td><span class="fw-bold">Next Tier Therms:</span> @strNext15Therms</td> <td><span class="fw-bold">Last Tier Therms:</span> @strAbove40Therms</td> </tr> </table> <hr /> <h3 class="fw-bold">Bill Values</h3> <hr /> <table class="w700" align="center"> <tr> <td class="w250 fw-bold">Water Usage Charges:</td> <td class="w150">@strWaterUsageCharges</td> <td class="fw-bold">Sewer Charges:</td> <td>@strSewerCharges</td> </tr> <tr> <td class="fw-bold">Environment Charges:</td> <td>@strEnvironmentCharges</td> <td class="fw-bold">Service Charges:</td> <td>@strServiceCharges</td> </tr> </table> <hr /> <table class="w700" align="center"> <tr> <td class="w250"></td> <td class="w150"></td> <td class="fw-bold">Total Charges:</td> <td>@strTotalCharges</td> </tr> </table> <hr /> <table class="w700" align="center"> <tr> <td class="w250"></td> <td class="fw-bold">Local Taxes:</td> <td>@strLocalTaxes</td> <td></td> <td class="fw-bold">State Taxes:</td> <td>@strStateTaxes</td> </tr> </table> <hr /> <table class="w700" align="center"> <tr> <td class="w250"></td> <td class="w150"></td> <td class="fw-bold">Amount Due:</td> <td>@strAmountDue</td> </tr> </table> </form> </div>
Introduction to if...else Conditions
If you use an if condition to perform an operation and if the result is true, we saw that you could execute the statement. Any other result would be ignored. To consider an alternative to an if condition, you can use a keyword named else. The formula to use it is:
if(condition) statement1; else statement2;
Once again, the condition can be a Boolean operation. If the condition is true, then the statement1 would execute. If the condition is false, then the compiler would execute the statement2 in the else section. Here is an example:
@{
int number = 248;
string result = "";
if(number == 248)
result = "That number is correct.";
else
result = "That number is not right.";
}
<p>@result</p>
This would produce:
That number is correct.
Practical Learning: Introducing if...else Conditions
@page @model StellarWaterPoint03.Pages.CustomerInvoiceModel @{ string accountType = ""; double counterReadingEnd = 0.00, counterReadingStart = 0.00, gallons = 0.00; double localTaxes = 0.00, stateTaxes = 0.00; double serviceCharges = 0.00, environmentCharges = 0.00; double first25Therms = 0.00, next15Therms = 0.00, above40Therms = 0.00; double waterUsageCharges = 0.00, sewerCharges = 0.00; double HCFTotal = 0.00, totalCharges = 0.00; string strHCFTotal = "0.00"; string strWaterUsageCharges = "0.00", strSewerCharges = "0.00"; string strServiceCharges = "0.00", strEnvironmentCharges = "0.00"; string strTotalCharges = "0.00", strAmountDue = "0.00"; string strStateTaxes = "0.00", strLocalTaxes = "0.00"; string strFirst25Therms = "0.00", strNext15Therms = "0.00", strAbove40Therms = "0.00"; if (Request.HasFormContentType) { accountType = Request.Form["AccountsTypes"]; counterReadingStart = double.Parse(Request.Form["txtCounterReadingStart"]); counterReadingEnd = double.Parse(Request.Form["txtCounterReadingEnd"]); gallons = counterReadingEnd - counterReadingStart; HCFTotal = gallons / 748; first25Therms = 25.00 * 1.5573; next15Therms = 15.00 * 1.2264; above40Therms = (HCFTotal - 40.00) * 0.9624; waterUsageCharges = first25Therms + next15Therms + above40Therms; sewerCharges = waterUsageCharges * 0.252; if (accountType == "residential") environmentCharges = waterUsageCharges * 0.0025; else environmentCharges = waterUsageCharges * 0.0125; if(accountType == "residential") serviceCharges = waterUsageCharges * 0.0328; else serviceCharges = waterUsageCharges * 0.11643; totalCharges = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges; if (accountType == "residential") localTaxes = totalCharges * 0.002857; else localTaxes = totalCharges * 0.005259; if(accountType == "residential") stateTaxes = totalCharges * 0.000815; else stateTaxes = totalCharges * 0.002262; strFirst25Therms = $"{first25Therms:F}"; strNext15Therms = $"{next15Therms:F}"; strAbove40Therms = $"{above40Therms:F}"; strHCFTotal = $"{HCFTotal:F}"; strWaterUsageCharges = $"{waterUsageCharges:F}"; strSewerCharges = $"{sewerCharges:F}"; strServiceCharges = $"{serviceCharges:F}"; strEnvironmentCharges = $"{environmentCharges:F}"; strTotalCharges = $"{totalCharges:F}"; strStateTaxes = $"{stateTaxes:F}"; strLocalTaxes = $"{localTaxes:F}"; strAmountDue = $"{(totalCharges + localTaxes + stateTaxes):F}"; } } . . .
In the flow of your code, you can jump from one statement or line to another. To make this possible, the C# language provides an operator named goto. Before using it, first create or insert a name on a particular section of code or in a method. The name, also called a label, is made of one word and it can be anything. That name is followed by a colon ":". Here is an example:
proposition:
In the same way, you can create as many labels as you want. The name of each label must be unique among the other labels in the same section of code (in the same scope). Here are examples:
proposition:
something:
TimeToLeave:
After creating the label(s), you can create a condition so that, when that condition is true, code execution would jump to a designated label. To do this, in the body of the condition, type goto followed by the label. Here are examples:
int nbr = 248; double result = 0; if(nbr is < 200) goto proposition; else goto something; proposition: result = 245.55; something: result = 105.75;
We have seen that an if...else conditional statement can be performed as follows:
if(condition) statement1; else statement2;
Here is an example of such a statement:
@{
double value;
string choice = "Residential";
if(choice == "Residential")
value = 16.55;
else
value = 19.25;
}
<pre>Account Type: Residential
Value: @value</pre>
This would produce:
Account Type: Residential.
If you have a condition that can be checked as an if situation with one alternate else, you can use the ternary operator that is a combination of ? and :. Its formula is:
condition ? statement1 : statement2;
The condition would first be checked. If the condition is true, then statement1 would execute. If not, statement2 would execute. Based on this, the above code can be written as follows:
@{
double value;
string choice = "Residential";
value = choice == "Residential" ? 16.55 : 19.25;
}
<pre>Account Type: Residential
Value: @value</pre>
If you want to make your code easy to read, you can (should) include the condition in parentheses. This can be done as follows:
@{
string choice = "Residential";
double value = (choice == "Residential") ? 16.55 : 19.25;
}
<pre>Account Type: Residential
Value: @value</pre>
One or each of the statements can use an expression. Here are examples:
double environmentCharges = (answer == "1") ? usage * 0.0025 : usage * 0.0125; double serviceCharges = (answer == "1") ? waterUsageCharges * 0.0328 : waterUsageCharges * 0.11643;
This time too, to make your code easy to read, you can include the statement in parenthese. Here are examples:
double environmentCharges = (answer == "1") ? (usage * 0.0025) : (usage * 0.0125); double serviceCharges = (answer == "1") ? (waterUsageCharges * 0.0328) : (waterUsageCharges * 0.11643);
Practical Learning: Using the Ternary Operator
@page @model StellarWaterPoint03.Pages.CustomerInvoiceModel @{ string accountType = ""; double counterReadingEnd = 0.00, counterReadingStart = 0.00, gallons = 0.00; double localTaxes = 0.00, stateTaxes = 0.00; double serviceCharges = 0.00, environmentCharges = 0.00; double first25Therms = 0.00, next15Therms = 0.00, above40Therms = 0.00; double waterUsageCharges = 0.00, sewerCharges = 0.00; double HCFTotal = 0.00, totalCharges = 0.00; string strHCFTotal = "0.00"; string strWaterUsageCharges = "0.00", strSewerCharges = "0.00"; string strServiceCharges = "0.00", strEnvironmentCharges = "0.00"; string strTotalCharges = "0.00", strAmountDue = "0.00"; string strStateTaxes = "0.00", strLocalTaxes = "0.00"; string strFirst25Therms = "0.00", strNext15Therms = "0.00", strAbove40Therms = "0.00"; if (Request.HasFormContentType) { accountType = Request.Form["AccountsTypes"]; counterReadingStart = double.Parse(Request.Form["txtCounterReadingStart"]); counterReadingEnd = double.Parse(Request.Form["txtCounterReadingEnd"]); gallons = counterReadingEnd - counterReadingStart; HCFTotal = gallons / 748; first25Therms = 25.00 * 1.5573; next15Therms = 15.00 * 1.2264; above40Therms = (HCFTotal - 40.00) * 0.9624; waterUsageCharges = first25Therms + next15Therms + above40Therms; sewerCharges = waterUsageCharges * 0.252; environmentCharges = (accountType == "residential") ? (waterUsageCharges * 0.0025) : (waterUsageCharges * 0.0125); serviceCharges = (accountType == "residential") ? (waterUsageCharges * 0.0328) : (waterUsageCharges * 0.11643); totalCharges = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges; localTaxes = (accountType == "residential") ? (totalCharges * 0.002857) : (totalCharges * 0.005259); stateTaxes = (accountType == "residential") ? (totalCharges * 0.000815) : (totalCharges * 0.002262); strFirst25Therms = $"{first25Therms:F}"; strNext15Therms = $"{next15Therms:F}"; strAbove40Therms = $"{above40Therms:F}"; strHCFTotal = $"{HCFTotal:F}"; strWaterUsageCharges = $"{waterUsageCharges:F}"; strSewerCharges = $"{sewerCharges:F}"; strServiceCharges = $"{serviceCharges:F}"; strEnvironmentCharges = $"{environmentCharges:F}"; strTotalCharges = $"{totalCharges:F}"; strStateTaxes = $"{stateTaxes:F}"; strLocalTaxes = $"{localTaxes:F}"; strAmountDue = $"{(totalCharges + localTaxes + stateTaxes):F}"; } } . . .
@page @model IndexModel @{ double grossSalary = 0.00; double taxAmount = 0.00; double netPay = 0.00; double taxRate = 0.00; string strGrossSalary = "0.00"; string strTaxAmount = "0.00"; string strNetPay = "0.00"; string strTaxRate = "0.00"; if (Request.HasFormContentType) { grossSalary = double.Parse(Request.Form["txtGrossSalary"]); taxAmount = grossSalary * taxRate / 100.00; netPay = grossSalary - taxAmount; strTaxAmount = $"{taxAmount:F}"; strGrossSalary = $"{grossSalary:F}"; strTaxRate = $"{taxRate:F}"; strNetPay = $"{netPay:F}"; } } <h1 style="text-align: center">- Amazing DeltaX - State Income Tax -</h1> <hr /> <h1 style="text-align: center">- Mississippi -</h1> <hr /> <form name="frmTaxPreparation" method="post"> <h3 style="text-align: center">Enter the information for tax preparation</h3> <hr /> <table style="width: 225px" align="center"> <tr> <td style="width: 125px">Gross Salary:</td> <td><input type="text" style="width: 100px" id="txtGrossSalary" name="txtGrossSalary" value="@grossSalary" /></td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Evaluate Taxes" name="btnEvaluateTaxes" style="width: 150px" /></td> </tr> </table> <hr /> <table style="width: 225px" align="center"> <tr style="border-bottom: 1px solid black"> <td>Gross Salary:</td> <td style="text-align: right">@strGrossSalary</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Tax Rate:</td> <td style="text-align: right">@strTaxRate</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Tax Amount:</td> <td style="text-align: right">@strTaxAmount</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Net Pay:</td> <td style="text-align: right">@strNetPay</td> </tr> </table> </form>
The Bodies of a Composite Conditional Statement
We saw that if the statement of an if condition is long or if it involves many statements, you can create a body for its statement(s). In the same way, if an else condition produces a long or many statements, add a body delimited by curly brackets to it. This would be done as follows:
if(condition) statement1; else { statement2; }
Either the if or the else statement can have a body whether the other has a body or not. You will decide based on your goal:
if(condition){ if-statement1; if-statement2; . . . if-statement_n; } else{ else-statement1; else-statement2; . . . else-statement_n; }
Variants of an else Conditional Statement
If you use an if...else situation, you can process only two statements. In some cases, you may deal with more than two conditions. In this case, you can use an if...else if condition. Its formula is:
if(condition1) statement1; else if(condition2) statement2;
If you want, you can add a body delimited by curly brackets, as follows:
if(condition1) { statement1; } else if(condition2) { statement2; }
The first condition, condition1, would first be checked. If condition1 is true, then statement1 would execute. If condition1 is false, then condition2 would be checked. If condition2 is true, then statement2 would execute. Any other result would be ignored.
Practical Learning: Using Else If
@page
@model IndexModel
@{
double grossSalary = 0.00;
double taxAmount = 0.00;
double netPay = 0.00;
double taxRate = 0.00;
string strGrossSalary = "0.00";
string strTaxAmount = "0.00";
string strNetPay = "0.00";
string strTaxRate = "0.00";
if (Request.HasFormContentType)
{
grossSalary = double.Parse(Request.Form["txtGrossSalary"]);
// Mississippi
if(grossSalary is >= 10_000)
taxRate = 5.00;
else if(grossSalary is >= 5_000)
taxRate = 4.00;
else if(grossSalary is >= 1_000)
taxRate = 3.00;
taxAmount = grossSalary * taxRate / 100.00;
netPay = grossSalary - taxAmount;
strTaxAmount = $"{taxAmount:F}";
strGrossSalary = $"{grossSalary:F}";
strTaxRate = $"{taxRate:F}";
strNetPay = $"{netPay:F}";
}
}
. . .
@page @model IndexModel @{ double grossSalary = 0.00; double taxAmount = 0.00; double netPay = 0.00; double taxRate = 0.00; string strStateAbbr = "", strStateName = ""; string strGrossSalary = "0.00"; string strTaxAmount = "0.00"; string strNetPay = "0.00"; string strTaxRate = "0.00"; if (Request.HasFormContentType) { strStateAbbr = Request.Form["selStates"]; grossSalary = double.Parse(Request.Form["txtGrossSalary"]); if(strStateAbbr == "CO") { taxRate = 4.63; strStateName = "Colorado"; } else if(strStateAbbr == "IN") { taxRate = 3.23; strStateName = "Indiana"; } else if(strStateAbbr == "MI") { taxRate = 4.25; strStateName = "Michigan"; } else if(strStateAbbr == "NC") { taxRate = 5.25; strStateName = "North Carolina"; } else if(strStateAbbr == "PA") { taxRate = 3.07; strStateName = "Pennsylvania"; } else if(strStateAbbr == "TN") { taxRate = 1.00; strStateName = "Tennessee"; } taxAmount = grossSalary * taxRate / 100.00; netPay = grossSalary - taxAmount; strTaxAmount = $"{taxAmount:F}"; strGrossSalary = $"{grossSalary:F}"; strTaxRate = $"{taxRate:F}"; strNetPay = $"{netPay:F}"; } } <h1 style="text-align: center">- Amazing DeltaX - State Income Tax -</h1> <hr /> <form name="frmTaxPreparation" method="post"> <table style="width: 250px" align="center"> <tr> <td style="width: 125px">Select a State:</td> <td> <select id="selStates" name="selStates"> <option value="CO">Colorado</option> <option value="IN">Indiana</option> <option value="MI">Michigan</option> <option value="NC">North Carolina</option> <option value="PA">Pennsylvania</option> <option value="TN">Tennessee</option> </select> </td> </tr> </table> <hr /> <table style="width: 250px" align="center"> <tr> <td style="width: 125px">Gross Salary:</td> <td><input type="text" style="width: 100px" id="txtGrossSalary" name="txtGrossSalary" value="@grossSalary" /></td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Evaluate Taxes" name="btnEvaluateTaxes" style="width: 150px" /></td> </tr> </table> <hr /> <table style="width: 250px" align="center"> <tr style="border-bottom: 1px solid black; border-top: 1px solid black"> <td>State:</td> <td style="text-align: right">@strStateName</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Gross Salary:</td> <td style="text-align: right">@strGrossSalary</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Tax Rate:</td> <td style="text-align: right">@strTaxRate</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Tax Amount:</td> <td style="text-align: right">@strTaxAmount</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Net Pay:</td> <td style="text-align: right">@strNetPay</td> </tr> </table> </form>
If... Else If... Else
Because there can be other alternatives, the C# language provides an alternate else condition as the last resort. Its formula is:
if(condition1) statement1; else if(condition2) statement2; else statement-n;
If you want, you can add a body delimited by curly brackets to any of the conditions:
if(condition1){ statement1; } else if(condition2) { statement2; } else { statement-n; }
Practical Learning: Introducing if...else if...else
@page @model StellarWaterPoint03.Pages.CustomerInvoiceModel @{ string accountType = ""; double counterReadingEnd = 0.00, counterReadingStart = 0.00, gallons = 0.00; double localTaxes = 0.00, stateTaxes = 0.00; double serviceCharges = 0.00, environmentCharges = 0.00; double first25Therms = 0.00, next15Therms = 0.00, above40Therms = 0.00; double waterUsageCharges = 0.00, sewerCharges = 0.00; double HCFTotal = 0.00, totalCharges = 0.00; string strHCFTotal = "0.00"; string strWaterUsageCharges = "0.00", strSewerCharges = "0.00"; string strServiceCharges = "0.00", strEnvironmentCharges = "0.00"; string strTotalCharges = "0.00", strAmountDue = "0.00"; string strStateTaxes = "0.00", strLocalTaxes = "0.00"; string strFirst25Therms = "0.00", strNext15Therms = "0.00", strAbove40Therms = "0.00"; if (Request.HasFormContentType) { accountType = Request.Form["AccountsTypes"]; counterReadingStart = double.Parse(Request.Form["txtCounterReadingStart"]); counterReadingEnd = double.Parse(Request.Form["txtCounterReadingEnd"]); gallons = counterReadingEnd - counterReadingStart; HCFTotal = gallons / 748; if (HCFTotal is > 40.00) { first25Therms = 25.00 * 1.5573; next15Therms = 15.00 * 1.2264; above40Therms = (HCFTotal - 40.00) * 0.9624; } else if (HCFTotal is > 25.00) { first25Therms = 25.00 * 1.5573; next15Therms = (HCFTotal - 25.00) * 1.2264; above40Therms = 0.00; } else // if (HCFTotal > 40.00) { first25Therms = HCFTotal * 1.5573; next15Therms = 0.00; above40Therms = 0.00; } waterUsageCharges = first25Therms + next15Therms + above40Therms; sewerCharges = waterUsageCharges * 0.252; environmentCharges = (accountType == "residential") ? (waterUsageCharges * 0.0025) : (waterUsageCharges * 0.0125); serviceCharges = (accountType == "residential") ? (waterUsageCharges * 0.0328) : (waterUsageCharges * 0.11643); totalCharges = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges; localTaxes = (accountType == "residential") ? (totalCharges * 0.002857) : (totalCharges * 0.005259); stateTaxes = (accountType == "residential") ? (totalCharges * 0.000815) : (totalCharges * 0.002262); strFirst25Therms = $"{first25Therms:F}"; strNext15Therms = $"{next15Therms:F}"; strAbove40Therms = $"{above40Therms:F}"; strHCFTotal = $"{HCFTotal:F}"; strWaterUsageCharges = $"{waterUsageCharges:F}"; strSewerCharges = $"{sewerCharges:F}"; strServiceCharges = $"{serviceCharges:F}"; strEnvironmentCharges = $"{environmentCharges:F}"; strTotalCharges = $"{totalCharges:F}"; strStateTaxes = $"{stateTaxes:F}"; strLocalTaxes = $"{localTaxes:F}"; strAmountDue = $"{(totalCharges + localTaxes + stateTaxes):F}"; } } . . .
If...Else If ... Else If and Else
The if...else conditional statement allows you to process many conditions. The formula to follow is:
if(condition1) statement1; else if(condition2) statement2; . . . else if(condition_n) statement_n;
If you are writing the code in a webpage, each statement must be included in curly brackets. The formula to follow is:
if(condition1) { statement1; } else if(condition2) { statement2; } . . . else if(condition_n) { statement_n; }
The conditions would be checked from the beginning one after another. If a condition is true, then its corresponding statement would execute.
If there is a possibility that none of the conditions would respond true, you can add a last else condition and its statement. The formula to follow is:
if(condition1) statement1; else if(condition2) statement2; . . . else if(condition_n) statement_n; else statement-n;
In a webpage, the formula to follow is:
if(condition1) { statement1; } else if(condition2) { statement2; } . . . else if(condition_n) { statement_n; } else { statement-n; }
A condition may need many statements to execute. In this case, you must delimit the statements by curly brackets:
if(condition1) { if-statement_1; if-statement_2; . . . if-statement_n; } else if(condition2) { else-if-1-statement_1; else-if-1-statement_2; . . . else-if-1-statement_n; } . . . else if(condition_n) { else-if-n-statement_1; else-if-n-statement_2; . . . else-if-n-statement_n; } else { else-statement_1; else-statement_2; . . . else-statement_n; }
Functions and Methods Conditional Returns
Introduction
When performing its assignment, a function can encounter different situations. You can make the function produce a result that depends on some condition(s).
Exiting from a Function
Consider the following code that contains a function that updates two variables:
@page
@model Valuable.Pages.FunctionalModel
@{
string strOne = "";
string strTwo = "";
void SetTicketAmount()
{
strOne = "Computer";
strTwo = "Science";
}
}
@{
SetTicketAmount();
}
<p>@strOne @strTwo</p>
This would produce:
Computer Science
Sometimes, for one reason or another, as a function is processing code in its body, you may want to get out of the function before the closing curly bracket of the function. To do this, where you to stop the processing, type the return keyword followed by a semicolon. Here is an example:
@page
@model Valuable.Pages.FunctionalModel
@{
string strOne = "";
string strTwo = "";
void SetTicketAmount()
{
strOne = "Computer";
return;
strTwo = "Science";
}
}
@{
SetTicketAmount();
}
<p>@strOne @strTwo</p>
In this case, when the compiler reaches the return; line, it gets out of the function and continues the processing outside that function. As a result, the above would produce:
Computer
Conditionally Returning a Variable
We are already familiar with the ability for a function to return a value. In some cases, the value you want to return is not a simple constant: It may depend on some condition. To make this happen, you have various options. In a function, you can create an if. You can store the value in a variable, and then return that variable. Here is an example:
@functions{
int SetTicketAmount(bool aggressive)
{
int fee = 45;
if (aggressive == true)
fee = 100;
return fee;
}
}
Of course, if you are using an or an if(something == true) condition, you can omit the == true section. Here is an example:
@functions{
int SetTicketAmount(bool aggressive)
{
int fee = 45;
if (aggressive)
fee = 100;
return fee;
}
}
And of course, you can use any of the available Boolean operators. Here is an example:
@functions{
int SpecifyDiscountRate(int days)
{
int rate = 15;
if (days > 30)
rate = 50;
return rate;
}
}
You can use any other appropriate Boolean operators such as is. Here is an example:
@functions{
int SpecifyDiscountRate(int days)
{
int rate = 15;
if(days is > 30)
rate = 50;
return rate;
}
}
You can use an if...else conditional statement that checks a condition in a function, store the result in a variable, and then return that result. Here is an example:
@functions{
int SpecifyDiscountRate(int days)
{
int rate;
if (days is <= 30)
rate = 15;
else
rate = 50;
return rate;
}
}
You can also use an if...else if or an if...else if...else conditional statement to check a condition. Here is an example:
@functions{ int SpecifyDiscountRate(int days) { int rate; if (days is > 70) rate = 70; else if(days is > 50) rate = 50; else if(days is > 30) rate = 35; else // if(days is > 15) rate = 15; return rate; } }
Returning from a Conditional Statement
Introduction
In the above examples, we first declared a variable to hold a value that will be returned from a function. If the processing in the function is not very intense, you don't need such a variable: in the body of each condition, you can use the return keyword followed by the value to return. Here are two examples:
@functions{ int SetTicketAmount(bool aggressive) { if (aggressive) return 100; else return 45; } int SpecifyDiscountRate(int days) { if (days is > 70) return 70; else if(days is > 50) return 50; else if(days is > 30) return 35; else // if(days is > 15) return 15; } }
Practical Learning: Conditionally Returning a Value
@page @model TaxPreparation01.Pages.wvModel @{ double grossSalary = 0.00; double CalculateTaxAmount() { /* https://tax.wv.gov/Documents/TaxForms/2020/it140.booklet.pdf * 1 - Single * 2 - Head of household * 3 - Married filing joint * 5 - Widow[er] with dependent child * Less than $10,000............3% of the taxable income * At least – But less than – * $ 10,000 $25,000 $300.00 plus 4% of excess over $10,000 * $ 25,000 $40,000 $900.00 plus 4.5% of excess over $25,000 * $ 40,000 $60,000 $1,575.00 plus 6% of excess over $40,000 * $ 60,000 $2,775.00 plus 6.5% of excess over $60,000 * */ if (grossSalary < 10_000) return grossSalary * 3.00 / 100; else if( (grossSalary >= 10_000) && (grossSalary < 25_000) ) return 300.00 + ((grossSalary - 10_000) * 4.00 / 100); else if ((grossSalary >= 25_000) && (grossSalary < 40_000)) return 900 + ((grossSalary - 25_000) * 4.50 / 100); else if ((grossSalary >= 40_000) && (grossSalary < 60_000)) return ((grossSalary - 40_000) * 6.00 / 100); else // if (grossSalary >= 60_000) return 2_775 + ((grossSalary - 60_000) * 6.50 / 100); } double CalculateNetPay() => grossSalary - CalculateTaxAmount(); string strGrossSalary = "0.00"; string strTaxAmount = "0.00"; string strNetPay = "0.00"; if (Request.HasFormContentType) { grossSalary = double.Parse(Request.Form["txtGrossSalary"]); strGrossSalary = $"{grossSalary:F}"; strTaxAmount = $"{CalculateTaxAmount():f}"; strNetPay = $"{CalculateNetPay():f}"; } } <h1 style="text-align: center">- Amazing DeltaX - State Income Tax -</h1> <hr /> <h1 style="text-align: center">-=- West Virginia -=-</h1> <hr /> <form name="frmTaxPreparation" method="post"> <h3 style="text-align: center">Enter the information for tax preparation</h3> <hr /> <table style="width: 225px" align="center"> <tr> <td style="width: 125px">Gross Salary:</td> <td><input type="text" style="width: 100px" id="txtGrossSalary" name="txtGrossSalary" value="@strGrossSalary" /></td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Evaluate Payroll" name="btnPrepareTax" style="width: 150px" /></td> </tr> </table> <hr /> <table style="width: 225px" align="center"> <tr style="border-bottom: 1px solid black; border-top: 1px solid black"> <td>Gross Salary:</td> <td style="text-align: right">@strGrossSalary</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Tax Amount:</td> <td style="text-align: right">@strTaxAmount</td> </tr> <tr style="border-bottom: 1px solid black"> <td>Net Pay:</td> <td style="text-align: right">@strNetPay</td> </tr> </table> </form>
Exiting Early from a Function
In a function, you can write any appropriate code before and after the return; line. If you do this, the code before the return; line in the function would execute, the code after the return; line would not execute (but that code must not contain errors). You can use this characteristic to write code that check a condition and, if the statement fulfills a certain condition, you can get out of the function even if there is other code in the function.
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2023, FunctionX | Thursday 06 October 2021 | Next |
|