Home

Introduction to Conditional Statements

if a Condition is True

Introduction

A conditional statement is an expression that produces a true or false result. To create the expression, you use the Boolean operators we studied in the previous lesson.

Creating a Boolean Condition

To check if an expression is true and use its Boolean result, you can use the if operator. The formula to follow is:

if(condition) statement;

The condition can be the type of Boolean operation we studied in the previous lesson. That is, it can have the following formula:

operand1 Boolean-operator operand2

If the condition produces a true result, then the statement executes. If the statement to execute is short, you can write it on the same line with the condition that is being checked. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html>
<head>
<script language="C#" runat="server">
void btnCalculateClick(object sender, EventArgs e)
{
        double pricePerCCF = 50.00;
        double monthlyCharges = 0.00;
        double consumption = double.Parse(txtConsumption.Text);

        if(consumption >= 0.50) pricePerCCF = 35.00;

        txtPricePerCCF.Text = pricePerCCF.ToString("F");

        pricePerCCF = double.Parse(txtPricePerCCF.Text);

        monthlyCharges = consumption * pricePerCCF;

        txtMonthlyCharges.Text  = monthlyCharges.ToString("F");
}
</script>
<title>Gas Utility Company</title>
</head>
<body>
<div align="center">

<form id="frmUtility" runat="server">
<h3>Gas Utility Company</h3>

<table border=0>
  <tr>
    <td>Consumption:</td>
    <td><asp:TextBox id="txtConsumption"
                                text="0" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td style="text-align: center"><asp:Button id="btnCalculate"
                              text="Calculate"
                              OnClick="btnCalculateClick"
                              runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Price Per CCF:</td>
    <td><asp:TextBox id="txtPricePerCCF" text="0" runat="server" /></td>
  </tr>
    <tr>
    <td>Monthly Charges:</td>
    <td><asp:TextBox id="txtMonthlyCharges" text="0" runat="server" /></td>
  </tr>
</table>
</form>
</div>
</body>
</html>

Here is an example of running the program:

Creating a Boolean Condition Creating a Boolean Condition
Creating a Boolean Condition Creating a Boolean Condition

If the statement is long, you can write it on a different line than the if condition. Here is an example:

<script language="C#" runat="server">
void btnCalculateClick(object sender, EventArgs e)
{
    double pricePerCCF = 50.00;
    double monthlyCharges = 0.00;
    double consumption = double.Parse(txtConsumption.Text);

    if(consumption >= 0.50)
        pricePerCCF = 35.00;

    txtPricePerCCF.Text = pricePerCCF.ToString("F");

    pricePerCCF = double.Parse(txtPricePerCCF.Text);

    monthlyCharges = consumption * pricePerCCF;

    txtMonthlyCharges.Text  = monthlyCharges.ToString("F");
}
</script>

You can also write the statement on its own line even if the statement is short enough to fit on the same line with the Condition.

If the statement spans more that one line, even if it is in one line, you can start with an openinig curly bracket and end it with a closing curly bracket. Here is an example:

<script language="C#" runat="server">
void btnCalculateClick(object sender, EventArgs e)
{
    double pricePerCCF = 50.00;
    double monthlyCharges = 0.00;
    double consumption = double.Parse(txtConsumption.Text);

    if(consumption >= 0.50)
    {
        pricePerCCF = 35.00;
    }

    txtPricePerCCF.Text = pricePerCCF.ToString("F");

    pricePerCCF = double.Parse(txtPricePerCCF.Text);

    monthlyCharges = consumption * pricePerCCF;

    txtMonthlyCharges.Text  = monthlyCharges.ToString("F");
}
</script>

If you omit the brackets, only the statement that immediately follows the condition would be executed. Just as you can create one if condition, you can write more than one.

if Something else Is True

To address an alternative to an if condition, you can use the else condition. The formula to follow is:

if(condition)
    statement1;
else
    statement2;

The condition can be a Boolean operation. If the condition is true, then statement1 would execute. If the condition is false, statement2 would execute. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html>
<head>
<script language="C#" runat="server">
void btnCalculateClick(object sender, EventArgs e)
{
    double weeklySalary = 0.00;
    double hourlySalary = double.Parse(txtHourlySalary.Text);
    double timeWorked   = double.Parse(txtTimeWorked.Text);

    if( timeWorked > 40.00 )
    {
        double overtime = timeWorked - 40.00;
        double overtimePay = hourlySalary * 1.50 * overtime;

        weeklySalary = (hourlySalary * 40.00) + overtimePay;
    }
    else
        weeklySalary = hourlySalary * timeWorked;

    txtWeeklySalary.Text = weeklySalary.ToString("F");
}
</script>
<title>Payroll Preparation</title>
</head>
<body>
<div align="center">

<form id="frmPayroll" runat="server">
<h3>Payroll Preparation</h3>

<table border=0>
  <tr>
    <td style="text-align: left">
        <asp:Label ID="lblHourlySalary" runat="server" Text="Hourly Salary:"></asp:Label>
      </td>
    <td style="text-align: left">
        <asp:TextBox id="txtHourlySalary" Width="65px"
                                text="0.00" runat="server" /></td>
  </tr>
  <tr>
    <td style="text-align: left">
        <asp:Label ID="lblTimeWorked" runat="server" Text="Time Worked:"></asp:Label></td>
    <td style="text-align: left">
        <asp:TextBox id="txtTimeWorked" text="0.00" runat="server" Width="65px" />
        <asp:Button id="btnCalculate"
                              text="Calculate"
                              OnClick="btnCalculateClick"
                              runat="server"></asp:Button></td>
  </tr>
    <tr>
    <td style="text-align: left">
        <asp:Label ID="lblWeeklySalary" runat="server" Text="Weekly Salary:"></asp:Label></td>
    <td style="text-align: left">
        <asp:TextBox id="txtWeeklySalary" text="0.00" Width="65px" runat="server" /></td>
  </tr>
</table>
</form>
</div>
</body>
</html>

Here is an example of using the webpage:

Creating a Boolean Condition Creating a Boolean Condition

Here is another example of using the webpage:

Creating a Boolean Condition Creating a Boolean Condition

Built-In Boolean Properties

Introduction

A property is referred to as Boolean if it can hold a value of true or false. Various classes and controls have many Boolean properties. Most of the time, you must write a conditional statement to find out what value the property has before taking appropriate actions.

Posting the Page Back

An interactive webpage allows a visitor to submit values that would be sent to the server. At one time, a visitor, may get a response back from the server, in which case the server may send new or updated values to display to the visitor. At any time, you may want to find out whether the page that is being presented to the visitor is freshly displaying or is rather a response from the server. To let you get this information, the Page class is equipped with a Boolean property named IsPostBack. Its values are as follows:

Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html>
<head>
<script language="C#" runat="server">
void Page_Load(object sender, EventArgs e)
{
        if (IsPostBack)
	    lblMessage.Text = "The webpage IS displaying as a POST BACK.";
        else
            lblMessage.Text = "The webpage is displaying for the first time.";
}

void btnCalculateClick(object sender, EventArgs e)
{
        double pricePerCCF = 50.00;
        double monthlyCharges = 0.00;
        double consumption = double.Parse(txtConsumption.Text);

        if(consumption >= 0.50) pricePerCCF = 35.00;

        txtPricePerCCF.Text = pricePerCCF.ToString("F");

        pricePerCCF = double.Parse(txtPricePerCCF.Text);

        monthlyCharges = consumption * pricePerCCF;

        txtMonthlyCharges.Text  = monthlyCharges.ToString("F");
}
</script>
<title>Gas Utility Company</title>
</head>
<body>
<div align="center">

<form id="frmUtility" runat="server">
<h3>Gas Utility Company</h3>

<table border=0>
  <tr>
    <td>Consumption:</td>
    <td><asp:TextBox id="txtConsumption"
                                text="0" runat="server" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td style="text-align: center"><asp:Button id="btnCalculate"
                              text="Calculate"
                              OnClick="btnCalculateClick"
                              runat="server"></asp:Button></td>
  </tr>
  <tr>
    <td>Price Per CCF:</td>
    <td><asp:TextBox id="txtPricePerCCF" text="0" runat="server" /></td>
  </tr>
    <tr>
    <td>Monthly Charges:</td>
    <td><asp:TextBox id="txtMonthlyCharges" text="0" runat="server" /></td>
  </tr>
</table>

<asp:Label id="lblMessage" runat="server"></asp:Label>
</form>
</div>
</body>
</html>

Options on Conditional Statements

The Ternary Operator

Imagine you have a (simple) if...else situation. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html>
<head>
<script language="C#" runat="server">
void btnEvaluateClick(object sender, EventArgs e)
{
    string decision = null;
    int  creditScore = int.Parse(txtCreditScore.Text);
    bool hasGoodCredit = (creditScore >= 680);

    if(hasGoodCredit == true)
        decision = "approved";
    else
        decision = "denied";

    lblMessage.Text = "Decision: The loan has been " + decision;
}
</script>
<title>Loan Evaluation</title>
</head>
<body>
<form id="frmGrade" runat="server">
<h3>Loan Evaluation</h3>

<p>Enter Customer Credit Score: 
   <asp:TextBox id="txtCreditScore" style="width: 60px"
                       Text="0" runat="server" />
   <asp:Button id="btnEvaluate"
                              text="Evaluate"
                              runat="server" OnClick="btnEvaluateClick"></asp:Button></p>
<p>
   <asp:Label id="lblMessage" runat="server" /></p>
</form>
</body>
</html>

As an alternative, you can use the ternary operator that is a combination of ? and :. Its formula is:

condition ? statement1 : statement2;

The condition would be tested. If the condition is true, then statement1 would execute. Otherwise, statement2 would execute. Here is an example:

<%@ Page Language="C#" %>

<!DOCTYPE html>
<html>
<head>
<script language="C#" runat="server">
void btnEvaluateClick(object sender, EventArgs e)
{
    string decision = null;
    int  creditScore = int.Parse(txtCreditScore.Text);
    bool hasGoodCredit = (creditScore >= 680);

    decision = (hasGoodCredit == true) ? "approved" : "denied";

    lblMessage.Text = "Decision: The loan has been " + decision;
}
</script>
<title>Loan Evaluation</title>
</head>
<body>
<form id="frmGrade" runat="server">
<h3>Loan Evaluation</h3>

<p>Enter Customer Credit Score: 
   <asp:TextBox id="txtCreditScore" style="width: 60px"
                       Text="0" runat="server" />
   <asp:Button id="btnEvaluate"
                              text="Evaluate"
                              runat="server" OnClick="btnEvaluateClick"></asp:Button></p>
<p>
   <asp:Label id="lblMessage" runat="server" /></p>
</form>
</body>
</html>

Here is an example of using the webpage:

The Ternary Operator
The Ternary Operator

Here is another example of using the webpage:

The Ternary Operator
The Ternary Operator

The Null-Coalescing Operator ??

Remember that, when declaring a variable of a primitive type, you can add a question mark to the data type to specify that the variable can have a nullable value. At one time, you may want to assign the value of such a variable to another variable. If the variable is holding null, it means it does not have a value, so assigning to another variable would be meaningless. A solution is to first check whether the variable is currently holding null or an actual value:

To support this, the C# language provides the null-coalescent operator: "??". The formula to use it is:

TargetVariable = OriginalVariable ?? AlternateValue;

You must have declared the OriginalVariable and it must be able to hold null, which is done by adding ? to it. You can first declare the TargetVariable or declare it when initializing it. Of course, both variables must be compatible. Here is an example of using the ?? operator:

<%
    double? distance = null;
    double? fromTo = null;

    // . . .

    fromTo = distance ?? 135.85;

    // . . .
%>

The fromTo = distance ?? 135.85; means that:

if...else if and if...else

An if...else conditional statement can process only two statements. If you need to process more condition, you can add an else if condition. The formula to follow is:

if(Condition1) Statement1;
else if(Condition2) Statement2;

The first condition, condition1, would 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.

If you need to process more than two conditions, you can add more else if sections. The formula to follow would be:

if(condition1)
    statement1;
else if(condition2)
    statement2;
else if(condition3)
    Statement3;
. . .
else if(condition-n)
    Statement-n;

If none of the conditions matches, you can add a last else condition. The formulas to follow are:

if(condition1)
    statement1;
else if(condition2)
    statement2;
else
    statement-n;
if(condition1)
    statement1;
else if(condition2)
    statement2;
else if(condition3)
    statement3;
. . .
else
    statement-else;

 


Previous Copyright © 2008-2016, FunctionX Next