Introduction to Conditional Statements
Introduction to Conditional Statements
Logical Operators
Not Equal
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
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, and Boolean variables. If both operands are different, the operation produces a true result. If they are the exact same, the operation produces false.
Practical Learning: Introducing Conditional Statements
.container { margin: auto; width: 580px; } .alignment { text-align: center } .left-col { width: 120px } .ctrl-formatting { width: 80px }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PayrollPreparation04.App_Code { static public class Calculations { public static double Add(double a, double b) { return a + b; } static public double Subtract(double a, double b) { return a - b; } public static double Multiply(double a, double b) { return a * b; } public static double Add5(double a, double b, double c, double d, double e) { return a + b + c + d + e; } public static double Multiply3(double a, double b, double c) { return a * b * c; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PayrollPreparation04.App_Code { public class TimeSheet { public double Monday { get; set; } public double Tuesday { get; set; } public double Wednesday { get; set; } public double Thursday { get; set; } public double Friday { get; set; } public TimeSheet() { Monday = 0.00; Tuesday = 0.00; Wednesday = 0.00; Thursday = 0.00; Friday = 0.00; } public TimeSheet(double mon, double tue, double wed, double thu, double fri) { Monday = mon; Tuesday = tue; Wednesday = wed; Thursday = thu; Friday = fri; } } }
A Value Greater Than Another: >
To find out if one value is greater than the other, you can use the > operator. Its formula is:
value1 > value2
Both operands, in this case value1 and value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value. Otherwise, the comparison renders false or null:
Practical Learning: Finding Out Whether a Value is Greater Than Another
@helper Evaluate(PayrollPreparation04.App_Code.TimeSheet ts, double hourlySalary) { string strNetPay = "0.00"; string strOvertime = "0.00"; string strTimeWorked = "0.00"; double overtime = 0.00; double overtimePay = 0.00; // mon + tue + wed + thu + fri double timeWorked = PayrollPreparation04.App_Code.Calculations.Add5(ts.Monday, ts.Tuesday, ts.Wednesday, ts.Thursday, ts.Friday); double netPay = hourlySalary * timeWorked; if (timeWorked > 40.00) { // timeWorked - 40.00 overtime = PayrollPreparation04.App_Code.Calculations.Subtract(timeWorked, 40.00); // hourlySalary * 1.50 * overtime overtimePay = PayrollPreparation04.App_Code.Calculations.Multiply3(hourlySalary, 1.50, overtime); // (hourlySalary * 40.00) + overtimePay netPay = PayrollPreparation04.App_Code.Calculations.Add(PayrollPreparation04.App_Code.Calculations.Multiply(hourlySalary, 40.00), overtimePay); } strOvertime = overtime.ToString("F"); strTimeWorked = timeWorked.ToString("F"); strNetPay = netPay.ToString("F"); <form name="frmPayrollPreparation" method="post"> <table> <tr> <td class="left-col">Time Worked:</td> <td><input type="text" name="txtTimeWorked" class="ctrl-formatting" value="@strTimeWorked" /></td> <td>Overtime:</td> <td><input type="text" name="txtOvertime" class="ctrl-formatting" value="@strOvertime" /></td> <td>Net Pay:</td> <td><input type="text" name="txtNetPay" class="ctrl-formatting" value="@strNetPay" /></td> </tr> </table> </form> }
<!DOCTYPE html> <html> <head> <title>Fun Department Store - Payroll Preparation</title> <link rel="stylesheet" type="text/css" href="~/Content/Site.css" </head> <body> <div class="container"> <h2 class="alignment">Fun Department Store</h2> <h3 class="alignment">Payroll Preparation</h3> @{ double hSalary = 0.00; PayrollPreparation04.App_Code.TimeSheet record = new PayrollPreparation04.App_Code.TimeSheet(); if (IsPost) { double mon = Convert.ToDouble(Request["txtMonday"]); double tue = Convert.ToDouble(Request["txtTuesday"]); double wed = Convert.ToDouble(Request["txtWednesday"]); double thu = Convert.ToDouble(Request["txtThursday"]); double fri = Convert.ToDouble(Request["txtFriday"]); hSalary = Convert.ToDouble(Request["txtHourlySalary"]); record = new PayrollPreparation04.App_Code.TimeSheet(mon, tue, wed, thu, fri); } } <form name="frmPayrollPreparation" method="post"> <table> <tr> <td class="left-col">Hourly Salary:</td> <td><input type="text" name="txtHourlySalary" class="ctrl-formatting" value="@hSalary" /></td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td>Monday</td> <td>Tuesday</td> <td>Wednesday</td> <td>Thursday</td> <td>Friday</td> </tr> <tr> <td> </td> <td><input type="text" name="txtMonday" class="ctrl-formatting" value="@record.Monday" /></td> <td><input type="text" name="txtTuesday" class="ctrl-formatting" value="@record.Tuesday" /></td> <td><input type="text" name="txtWednesday" class="ctrl-formatting" value="@record.Wednesday" /></td> <td><input type="text" name="txtThursday" class="ctrl-formatting" value="@record.Thursday" /></td> <td><input type="text" name="txtFriday" class="ctrl-formatting" value="@record.Friday" /></td> </tr> <tr> <td> </td> <td colspan="5" style="text-align: center; height: 32px;"><input type="submit" name="btnCalculate" style="width: 300px" value="Calculate" /></td> </tr> </table> </form> @PayrollProcessing.Evaluate(@record, @hSalary) </div> </body> </html>
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 >= Value2
The comparison is performed on both operands: Value1 and Value2:
Practical Learning: Finding Out Whether a Value is Greater or Equal
static public class Calculations { public static double Multiply(double a, double b) { return a * b; } }
@helper Calculate(double consumption) { double pricePerCCF = 0.00; string strPricePerCCF = "0.00"; string strMonthlyCharges = "0.00"; if (consumption >= 0.50) { pricePerCCF = 35.00; } double monthlyCharges = GasUtilityCompany1.App_Code.Calculations.Multiply(consumption, pricePerCCF); strPricePerCCF = pricePerCCF.ToString("F"); strMonthlyCharges = monthlyCharges.ToString("F"); <form name="frmGasCompany" method="post"> <table> <tr> <td style="width: 120px">Price Per CCF</td> <td><input type="text" name="txtPricePerCCF" value="@strPricePerCCF" /></td> </tr> <tr> <td>Monthly Charges:</td> <td><input type="text" name="txtMonthlyCharges" value="@strMonthlyCharges" /></td> </tr> </table> </form> }
<!DOCTYPE html> <html> <head> <title>Gas Utility Company</title> <style> .container { margin: auto; width: 300px } </style> </head> <body> <div class="container"> <h2>Gas Utility Company</h2> @{ double consumption = 0.00; if (IsPost) { consumption = Convert.ToDouble(Request["txtConsumption"]); } } <form name="frmGasCompany" method="post"> <table> <tr> <td style="width: 120px">Consumption:</td> <td><input type="text" name="txtConsumption" value="@consumption" /></td> </tr> <tr> <td> </td> <td style="height: 32px;"><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> </table> </form> @Utilities.Calculate(@consumption) </div> </body> </html>
Less Than: <
To find out whether one value is lower than another, use the < operator. Its formula is:
Value1 < Value2
Less Than or Equal To: <=
The previous two 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 <= 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 or positive. 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.
Negating a Logical Operation or Value
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 | == |
< | Less than | 25 < 84 | >= |
<= | Less than or equal to | Cab <= Tab | > |
> | Greater than | 248 > 55 | <= |
>= | Greater than or equal to | Val1 >= Val2 | < |
The Logical NOT Operator
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 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 let you address an alternative to an if condition, the C# language provides a keyword named else. The formula to use it is:
if(condition) statement1; else statement2;
If you are writing the condition in a view, each statement must be included in a body deliminated by curcly brackets. As a result, the formula to follow 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 statement1 would be ignored.
Properties and Conditional Statements
A Conditional Statement in a Property Writer
A property writer allows external objects to provide a value to its corresponding field in the class. Because of this, and since it is through the writer that the external objects may change the value of the field, you can use the property writer to validate or reject a new value assigned to the field. Remember that the client objects of the class can only read the value of the field through the read property. Therefore, there may be only little concern on that side. Here is an example:
public class TimeSheet
{
private double day;
public double Overtime
{
get
{
return day;
}
set
{
// A day contains only 24 hours. There is no way somebody can work over 24 hours.
if( day > 24 )
day = 0.00;
else
day = value;
}
}
}
Validating the Value of a Property Before Returning it
The read side of a property is made to return a value. In some cases, you must process the value or check a condition to decide what to return. To provide this functionality, you can create a conditional statement in the property reader to decide what to return. Here is an example:
public class TimeSheet
{
private double day;
public double Overtime
{
get
{
if (day <= 8.00)
return 0.00;
else
return day - 8.00;
}
set
{
if( day > 24 )
day = 0.00;
else
day = value;
}
}
}
A Simple Read-Only Property
Remember that a read-only property has only a get clause. Here is an example:
public class Prism
{
public double Volume { get; }
}
As seen previously, some read-only properties contain many or a few lines of code to validate or process their values. In the body of such a property, you can create a conditional statement that makes a value as to what to return. In the body of a clause, you can also declare variables.
Practical Learning: Finding Out Whether a Value is Greater Than Another
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PayrollPreparation05.App_Code
{
public class TimeSheet
{
public double Monday { get; set; }
public double Tuesday { get; set; }
public double Wednesday { get; set; }
public double Thursday { get; set; }
public double Friday { get; set; }
public TimeSheet()
{
Monday = 0.00;
Tuesday = 0.00;
Wednesday = 0.00;
Thursday = 0.00;
Friday = 0.00;
}
public TimeSheet(double mon, double tue,
double wed, double thu, double fri)
{
Monday = mon;
Tuesday = tue;
Wednesday = wed;
Thursday = thu;
Friday = fri;
}
public double MondayOvertime
{
get
{
if (Monday <= 8.00)
return 0.00;
else
return Monday - 8.00;
}
}
public double TuesdayOvertime
{
get
{
if (Tuesday <= 8.00)
return 0.00;
else
return Tuesday - 8.00;
}
}
public double WednesdayOvertime
{
get
{
if (Wednesday <= 8.00)
return 0.00;
else
return Wednesday - 8.00;
}
}
public double ThursdayOvertime
{
get
{
if (Thursday <= 8.00)
return 0.00;
else
return Thursday - 8.00;
}
}
public double FridayOvertime
{
get
{
if (Friday <= 8.00)
return 0.00;
else
return Friday - 8.00;
}
}
}
}
<!DOCTYPE html> <html> <head> <title>Fun Department Store - Payroll Preparation</title> <style> .container { margin: auto; width: 550px; } </style> </head> <body> <div class="container"> <h2 style="text-align: center">Fun Department Store</h2> <h3 style="text-align: center">Payroll Preparation</h3> @{ string strMondayOvertime = "0.00"; string strTuesdayOvertime = "0.00"; string strFridayOvertime = "0.00"; string strWednesdayOvertime = "0.00"; string strThursdayOvertime = "0.00"; PayrollPreparation05.App_Code.TimeSheet ts = new PayrollPreparation05.App_Code.TimeSheet(); if (IsPost) { double mon = Convert.ToDouble(Request["txtMonday"]); double tue = Convert.ToDouble(Request["txtTuesday"]); double wed = Convert.ToDouble(Request["txtWednesday"]); double thu = Convert.ToDouble(Request["txtThursday"]); double fri = Convert.ToDouble(Request["txtFriday"]); ts = new PayrollPreparation05.App_Code.TimeSheet(mon, tue, wed, thu, fri); strMondayOvertime = ts.MondayOvertime.ToString("F"); strTuesdayOvertime = ts.TuesdayOvertime.ToString("F"); strWednesdayOvertime = ts.WednesdayOvertime.ToString("F"); strThursdayOvertime = ts.ThursdayOvertime.ToString("F"); strFridayOvertime = ts.FridayOvertime.ToString("F"); } } <form name="frmPayrollPreparation" method="post"> <table> <tr> <td> </td> <td>Monday</td> <td>Tuesday</td> <td>Wednesday</td> <td>Thursday</td> <td>Friday</td> </tr> <tr> <td>Time Workd:</td> <td><input type="text" name="txtMonday" style="width: 80px" value="@ts.Monday" /></td> <td><input type="text" name="txtTuesday" style="width: 80px" value="@ts.Tuesday" /></td> <td><input type="text" name="txtWednesday" style="width: 80px" value="@ts.Wednesday" /></td> <td><input type="text" name="txtThursday" style="width: 80px" value="@ts.Thursday" /></td> <td><input type="text" name="txtFriday" style="width: 80px" value="@ts.Friday" /></td> </tr> <tr> <td> </td> <td colspan="5" style="text-align: center; height: 32px;"><input type="submit" name="btnCalculate" style="width: 300px" value="Calculate" /></td> </tr> <tr> <td>Overtimes:</td> <td><input type="text" name="txtMondayOvertime" style="width: 80px" value="@strMondayOvertime" /></td> <td><input type="text" name="txtTuesdayOvertime" style="width: 80px" value="@strTuesdayOvertime" /></td> <td><input type="text" name="txtWednesdayOvertime" style="width: 80px" value="@strWednesdayOvertime" /></td> <td><input type="text" name="txtThursdayOvertime" style="width: 80px" value="@strThursdayOvertime" /></td> <td><input type="text" name="txtFridayOvertime" style="width: 80px" value="@strFridayOvertime" /></td> </tr> </table> </form> </div> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WaterDistributionCompany2.App_Code { public class WaterBill { private double ending; private double beginning; public WaterBill() { ending = 0.00; beginning = 0.00; } public WaterBill(string mSize, double counterStart, double counterEnd) { MeterSize = mSize; ending = counterEnd; beginning = counterStart; } public string MeterSize { get; set; } public double WaterUsage { get { return ending - beginning; } } public double WaterUseCharges { get { return WaterUsage * 4.18 / 1000; } } public double SewerUseCharges { get { return WaterUsage * 5.85 / 1000; } } public double DistributationCharges { get { double meterCharge = 0.00; double ratioWaterCharge = (WaterUseCharges + SewerUseCharges) / 5.00; if (MeterSize == "3/4") meterCharge = 4.15; else meterCharge = 6.38; return ratioWaterCharge + meterCharge; } } public double EnvironmentCharge { get { return ((WaterUseCharges + SewerUseCharges) / 7.00) * 1.85; } } public double TotalCharges { get { return WaterUseCharges + SewerUseCharges + DistributationCharges + EnvironmentCharge; } } } }
<!DOCTYPE html> <html> <head> <style> .container { margin: auto; width: 550px; } </style> <title>Water Distribution Company - Bill Preparation</title> </head> <body> <div class="container"> <h2 style="text-align: center">Water Distribution Company</h2> <h3 style="text-align: center">Bill Preparation</h3> </div> @{ string strTotalCharges = ""; string strMeterReadingEnd = ""; string strWaterUseCharges = ""; string strSewerUseCharges = ""; string strWaterSewerUsage = ""; string strMeterReadingStart = ""; string strEnvironmentCharges = ""; string strDistributionCharges = ""; WaterDistributionCompany2.App_Code.WaterBill waterSewerUsage = new WaterDistributionCompany2.App_Code.WaterBill(); if (IsPost) { string strMeterSize = Request["rdoMeterSize"]; int meterReadingStart = Request["txtMeterReadingStart"].AsInt(); int meterReadingEnd = Request["txtMeterReadingEnd"].AsInt(); waterSewerUsage = new WaterDistributionCompany2.App_Code.WaterBill(mSize: strMeterSize, counterStart: meterReadingStart, counterEnd: meterReadingEnd); strMeterReadingStart = meterReadingStart.ToString(); strMeterReadingEnd = meterReadingEnd.ToString(); strWaterSewerUsage = waterSewerUsage.WaterUsage.ToString(); strWaterUseCharges = waterSewerUsage.WaterUseCharges.ToString("F"); strSewerUseCharges = waterSewerUsage.SewerUseCharges.ToString("F"); strDistributionCharges = waterSewerUsage.DistributationCharges.ToString("F"); strEnvironmentCharges = waterSewerUsage.EnvironmentCharge.ToString("F"); strTotalCharges = waterSewerUsage.TotalCharges.ToString("F"); } } <div align="center"> <form name="fromBillPreparation" method="post"> <table style="width: 550px"> <tr> <td colspan="5" style="text-align: center; font-weight: bold">Meter Size</td> </tr> <tr> <td><input type="radio" name="rdoMeterSize" value="3/4" /> 3/4</td> <td><input type="radio" name="rdoMeterSize" value="1" /> 1</td> <td><input type="radio" name="rdoMeterSize" value="1 1/5" /> 1 1/5 </td> <td><input type="radio" name="rdoMeterSize" value="2" /> 2</td> <td><input type="radio" name="rdoMeterSize" value="3" /> 3</td> </tr> </table> <table style="width: 550px"> <tr> <td colspan="2"><hr /></td> </tr> <tr> <td style="width: 325px; font-weight: bold">Meter Reading Start:</td> <td><input type="text" name="txtMeterReadingStart" value="@strMeterReadingStart" /> Gallons</td> </tr> <tr> <td style="width: 325px; font-weight: bold">Meter Reading End:</td> <td><input type="text" name="txtMeterReadingEnd" value="@strMeterReadingEnd" /> Gallons</td> </tr> <tr> <td> </td> <td><input type="submit" name="txtCalculate" value="Calculate" /></td> </tr> <tr> <td colspan="2"><hr /></td> </tr> <tr> <td style="width: 325px; font-weight: bold">Water and Sewer Usage:</td> <td><input type="text" name="txtWaterSewerUsage" value="@strWaterSewerUsage" /> Gallons</td> </tr> <tr> <td style="width: 200px; font-weight: bold">Water Use Charges => 4.18 per 1,000 Gallons:</td> <td><input type="text" name="txtWaterUseCharges" value="@strWaterUseCharges" /></td> </tr> <tr> <td style="font-weight: bold">Sewer Use Charges => 5.85 per 1,000 Gallons:</td> <td><input type="text" name="txtSewerUseCharges" value="@strSewerUseCharges" /></td> </tr> <tr> <td style="width: 200px; font-weight: bold">Distribution Charges:</td> <td><input type="text" name="txtDistributionCharges" value="@strDistributionCharges" /></td> </tr> <tr> <td style="font-weight: bold">Environment Charges:</td> <td><input type="text" name="txtEnvironmentCharges" value="@strEnvironmentCharges" /></td> </tr> <tr> <td colspan="2"><hr /></td> </tr> <tr> <td style="font-weight: bold">Total Charges:</td> <td><input type="text" name="txtTotalCharges" value=@strTotalCharges /></td> </tr> </table> </form> </div> </body> </html>
A Property with a Simple Return Statement
Most read-only properties contain a single line of code that returns their values. Such properties don't need a body delimited by curly brackets. For such a property, replace the opening curly bracket with the => operator, replace the get { return expression with the statement to return, and omit the closing curly bracket.
Practical Learning: Creating and Using Read-Only Properties
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WaterDistributionCompany2.App_Code { public class WaterBill { private double ending; private double beginning; public WaterBill() { ending = 0.00; beginning = 0.00; } public WaterBill(string mSize, double counterStart, double counterEnd) { MeterSize = mSize; ending = counterEnd; beginning = counterStart; } public string MeterSize { get; set; } public double WaterUsage => ending - beginning; public double WaterUseCharges => WaterUsage * 4.18 / 1000; public double SewerUseCharges => WaterUsage * 5.85 / 1000; public double DistributationCharges { get { double meterCharge = 0.00; double ratioWaterCharge = (WaterUseCharges + SewerUseCharges) / 5.00; if (MeterSize == "3/4") meterCharge = 4.15; else meterCharge = 6.38; return ratioWaterCharge + meterCharge; } } public double EnvironmentCharge => ((WaterUseCharges + SewerUseCharges) / 7.00) * 1.85; public double TotalCharges => WaterUseCharges + SewerUseCharges + DistributationCharges + EnvironmentCharge; } }
Accessing the Boolean Value of a Property
As seen in previous lessons and sections, when creating a property, you can indicate its default value. You can do this in a constructor of its class. When it comes to a Boolean Property, you can give it a default value of tru or false depending on your goals. Here are two examples, one property with get and set accessors, and one automatic property:
public class VehicleInspection { private bool brightLights; public VehicleInspection() { brightLights = true; WindshieldWipersTurnWell = true; } public bool HeadlightsAreBright { get { return brightLights; } set { brightLights = value; } } public bool WindshieldWipersTurnWell { get; set; } }
As done with variables of other types, to check the value of a property, you can use an if conditional statement. When it comes to a Boolean property, you can compare it to a true or a false value. Here is an example done inside a method of a class:
public class VehicleInspection
{
private bool brightLights;
public VehicleInspection()
{
brightLights = true;
WindshieldWipersTurnWell = true;
}
public bool HeadlightsAreBright
{
get
{
return brightLights;
}
set
{
brightLights = value;
}
}
public bool WindshieldWipersTurnWell { get; set; }
public string PresentInspectionStatus()
{
if (brightLights == true)
return "Inspection proceeding smoothly";
return "Unknown Status";
}
}
Of course, if you are accessing the property outside its class, you must qualify it using a variable of the class. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>State Vehicle Inspection</title>
</head>
<body>
@{
VehicleInspection vi = new VehicleInspection();
}
<h3>State Vehicle Inspection</h3>
@if( vi.HeadlightsAreBright == true )
{
<p>Functioning Headlights: @vi.HeadlightsAreBright</p>
}
</body>
</html>
Like it was mentioned for regular variables, if you comparing the value of a Boolean property to know if it is true, you can omit the == true expression. Here is an example inside a method:
public class VehicleInspection
{
private bool brightLights;
public VehicleInspection()
{
brightLights = true;
WindshieldWipersTurnWell = true;
}
public bool HeadlightsAreBright
{
get
{
return brightLights;
}
set
{
brightLights = value;
}
}
public bool WindshieldWipersTurnWell { get; set; }
public string PresentInspectionStatus()
{
if (brightLights == true)
return "Inspection proceeding smoothly";
return "Unknown Status";
}
public string ValidateWindshields()
{
if (WindshieldWipersTurnWell)
return "Windshields alright";
return "Unknown Status";
}
}
Remember that if you are working outside the class, you must qualify the property. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>State Vehicle Inspection</title>
</head>
<body>
@{
VehicleInspection vi = new VehicleInspection();
}
<h3>State Vehicle Inspection</h3>
@if( vi.HeadlightsAreBright == true)
{
<p>Functioning Headlights: @vi.HeadlightsAreBright</p>
}
@if(vi.WindshieldWipersTurnWell)
{
<p>Windshield Wipers Turn Well: @vi.WindshieldWipersTurnWell</p>
}
</body>
</html>
Checking for Nullity
Comparing an Object to Nullity
Consider two classes as folows:
public class House { public string Bedrooms; } public class Description { public string View(House prop) { return prop.Bedrooms; } }
If a variable of a class was previously used but has been removed from memory, the variable has become null. Sometimes, you will be interested to find out whether an object is null. To perform this operation, you can compare the object to the null value. Here is an example:
using static System.Console;
public class House
{
public string Bedrooms;
}
public class Exercise
{
static int Main()
{
House habitat = null;
WriteLine("Real Estate");
WriteLine("House Description");
if (habitat == null)
WriteLine("There is no way to describe this house.");
WriteLine("==========================================");
return 0;
}
}
On the other hand, to find out whether an object is not null, you can use the != operator with the null keyword as the right operand. Here is an example:
<!DOCTYPE html> <html> <head> <title>Real Estate</title> </head> <body> @{ Description desc = new Description(); House habitat = new House(); habitat.Bedrooms = "5"; } <h3>Real Estate</h3> <h4>House Description</h4> @if (habitat != null) { <p>Number of Bedrooms: @desc.View(habitat)</p> } </body> </html>
Obviously the reason you are checking the nullity of an object is so you can take an appropriate action one way or another. Here is an example:
<!DOCTYPE html> <html> <head> <title>Real Estate</title> </head> <body> @{ Description desc = new Description(); House habitat = new House(); habitat.Bedrooms = "5"; } <h3>Real Estate</h3> @if(habitat == null) { <p>Apparently this house has not (yet) been built.</p> } else { <p>Number of Bedrooms: @desc.View(habitat)</p> } </body> </html>
The Null-Conditional Operator
Consider a class used to describe some houses:
public class House { public int Bedrooms; public House() { Bedrooms = 1; } }
We already saw how to find out whether an object of such a class is currently valid. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Real Estate</title>
</head>
<body>
@{
int beds = -1;
House habitat = null;
Description desc = new Description();
if (habitat == null)
{
beds = 0;
}
else
{
beds = habitat.Bedrooms;
}
}
<h3>Real Estate</h3>
<h4>House Description</h4>
<p>Number of Bedrooms: @beds</p>
</body>
</html>
In this case, we are trying to access a member of the class (getting the value of a property) only if the object is null. To simplify this operation, the C# language provides the null-conditional operator represented as ?. (the question mark immediately followed by a period). To apply it, use it to access the member of a class. Here is an example:
<!DOCTYPE html> <html> <head> <title>Real Estate</title> </head> <body> @{ int ? beds = 0; House habitat = null; Description desc = new Description(); beds = habitat?.Bedrooms; } <h3>Real Estate</h3> <h4>House Description</h4> <p>Number of Bedrooms: @beds</p> </body> </html>
Here is another version of the code:
<!DOCTYPE html>
<html>
<head>
<title>Real Estate</title>
</head>
<body>
@{
int ?beds = -1;
Description desc = new Description();
House habitat = new House();
habitat.Bedrooms = 5;
beds = habitat?.Bedrooms;
}
<h3>Real Estate</h3>
<h4>House Description</h4>
<p>Number of Bedrooms: @beds</p>
</body>
</html>btnSubmit
The ?. operator checks whether the variable on its left is currently holding a null value. If it is, nothing happens. If it doesn't, then the member on its right is accessed and the operation that must be performed proceeds.
The Null Coalescing Operator
The ?. operator is used to simply check the nullity of a variable. You must apply the subsequent statement separately. To make it possible to combine the ?. operation and its subsequent statement, the C# language provides the null coalescent operator represented as ?? (Two question marks). To apply it, type it after the condition followed by the desired statment. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Real Estate</title>
</head>
<body>
@{
int ?beds = -1;
Description desc = new Description();
House habitat = null;
beds = habitat?.Bedrooms ?? 0;
}
<h3>Real Estate</h3>
<h4>House Description</h4>
<p>Number of Bedrooms: @beds</p>
</body>
</html>
This code states that if the House object is null, the beds variable should be assigned 0. If the House object is not null, then the beds variable should receive a value from the designated property of the House class:
<!DOCTYPE html> <html> <head> <title>Real Estate</title> </head> <body> @{ int ?beds = -1; Description desc = new Description(); House habitat = new House(); habitat.Bedrooms = 5; beds = habitat?.Bedrooms ?? 0; } <h3>Real Estate</h3> <h4>House Description</h4> <p>Number of Bedrooms: @beds</p> </body> </html>
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|