Fundamentals of Boolean Values

Introduction

A value is said to be Boolean if it is true or it is false. In fact, the two available Boolean values are true and false.

Practical LearningPractical Learning: Introducing Boolean Values

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle list, click ASP.NET Web Application (.NET Framework) and set the project Name to Chemistry06
  4. Click OK
  5. In the New ASP.NET Web Application, make sure Empty is selected and click OK
  6. In the Solution Explorer, make sure Chemistry06 is selected. If not, click it.
    On the main menu, click Project -> Add -> New Folder
  7. Type Content and press Enter
  8. In the Solution Explorer, right-click Content -> Add -> New Item...
  9. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click Style Sheet
  10. Replace the name with Site
  11. Click Add
  12. Change the code as follows:
    body {
        margin: 0;
        background-color: #FFFFFF;
    }
    
    #top-banner {
        top: 0;
        width: 100%;
        height: 60px;
        position: fixed;
        background-color: #003366;
        border-bottom: 5px solid black;
    }
    
    .title-holder {
        top: 65px;
        width: 100%;
        height: 34px;
        position: fixed;
    }
    
    .container {
        width: 300px;
        margin: auto;
        padding-top: 10px;
    }
    
    .item-selection {
        width: 300px;
        margin: auto;
        padding-top: 120px;
    }
    
    #main-title {
        font-weight: 800;
        margin-top: 16px;
        font-size: 2.12em;
        text-align: center;
        color: antiquewhite;
        font-family: Garamond, 'Times New Roman', Georgia, serif
    }
    
    #sub-title {
        color: navy;
        font-weight: 600;
        padding-top: 2px;
        font-size: 1.68em;
        text-align: center;
        font-family: Garamond, 'Times New Roman', Georgia, serif
    }
    
    .small-text { width:       40px;  }
    .emphasize  { font-weight: bold;  }
    .left-col   { width:       120px; }
  13. In the Solution Explorer, right-click Chemistry05 -> Add -> Add ASP.NET Folder -> App_Code
  14. In the Solution Explorer, right-click Chemistry05 -> Add -> New Item...
  15. In the left frame of the Add New Item dialog box, expand Web and click Razor
  16. In the middle list, click Helper (Razor v3)
  17. Replace the name with ElementsProcessing
  18. Click Add
  19. In the Solution Explorer, right-click App_Code -> Add -> Class...
  20. Replace the name with Element
  21. Click Add
  22. Change the code as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace Chemistry06.App_Code
    {
        public enum Phase
        {
            Gas,
            Liquid,
            Solid,
            Unknown
        }
    
        public class Element
        {
            public string  Symbol       { get; set; } = "H";
            public string  ElementName  { get; set; } = "Hydrogen";
            public int     AtomicNumber { get; set; } = 1;
            public decimal AtomicWeight { get; set; } = 1.008M;
            public Phase   Phase        { get; set; } = Phase.Gas;
    
            public Element()
            {
            }
    
            public Element(int number)
            {
                AtomicNumber = number;
            }
    
            public Element(string symbol)
            {
                Symbol = symbol;
            }
    
            public Element(int number, string symbol, string name, decimal mass)
            {
                Symbol = symbol;
                ElementName = name;
                AtomicWeight = mass;
                AtomicNumber = number;
            }
        }
    }
  23. In the Solution Explorer, right-click Home -> Add -> New Item...
  24. In the left list, expand Web and click Razor
  25. In the middle list, click Web Page (Razor v3)
  26. Change the name to Index
  27. Click Add

A Boolean Variable

To let you declare a Boolean variable, C# provides a data type named bool. Here is an example of declaring a Boolean variable:

@{
    bool drinkingUnderAge;
}

To initialize a Boolean variable or to change its value, assign true or false to it.

A Boolean Field

Like the other types of variables we used in previous lessons, a Boolean variable can be made a field of a class. To create a Boolean field, declare a variable of type bool in the body of a class. Here is an example:

public class House
{
    bool hasCarGarage;
}

Presenting a Boolean Value

To display the value of a Boolean variable, you can type its name as the value of a control or in an HTML tag. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Accident Report</title>
</head>
<body>
<h3>Accident Report</h3>

@{ 
    bool drinkingUnderAge = true;
}

<p>The teenage driver was drinking under age: @drinkingUnderAge</p>
</body>
</html>

As is the case for all types, to declare a Boolean variable, you can use the var keyword. In this case, you must immediately initialize it.

Getting the Value of a Boolean Variable

As reviewed for the other data types, you can request the value of a Boolean variable from your webpage visitor. To support this, the Convert class is equipped with a method named ToBoolean. It takes as argument the value to be converted. On the other hand, you can use Request["value-to-convert"].AsBool(). Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Chemistry - Sodium</title>
</head>
<body>
@{
    bool underAge = false;
    bool intoxicated = false;

    if (IsPost)
    {
        underAge = Convert.ToBoolean(Request["txtUnderAge"]);
        intoxicated = Request["txtDrivingWhileIntoxicated"].AsBool();
    }
}

<div align="center">
  <h2>Accident Report</h2>

    <form name="frmAccidentReport" method="post">
        <table>
            <tr>
                <td style="font-weight: bold">The student was under age (True/False):</td>
                <td><input type="text" name="txtUnderAge" /></td>
            </tr>
            <tr>
                <td style="font-weight: bold">The driver was intoxicated (True/False):</td>
                <td><input type="text" name="txtDrivingWhileIntoxicated" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="btnSubmit" value="Submit" /></td>
            </tr>
        </table>
    </form>
</div>

<p>The student driver was under age: @underAge<br />
   The drinking was intoxicated: @intoxicated</p>
</body>
</html>

A Boolean Parameter

Like parameters of the other types, you can create a method that uses a parameter of bool type. Here is an example:

public class Contractor
{
    private void CalculatePayroll(bool fullTime)
    {
    
    }
}

In the body of the method, the parameter is treated as holding a true or false value. When calling the method, pass such a value or a variable that holds that value. Here is an example:

public class Contractor
{
    private void CalculatePayroll(bool fullTime)
    {

    }

    private void ValidateEmploymentStatus()
    {
        CalculatePayroll(false);
    }
}

Of course, a constructor can also use a Boolean parameter. Here is an example:

public class Contractor
{
    public Contractor(bool validated)
    {

    }

    private void CalculatePayroll(bool fullTime)
    {

    }

    private void ValidateEmploymentStatus()
    {
        CalculatePayroll(true);
    }
}

public class Accountability
{
    public Accountability()
    {
        Contractor empl = new Contractor(true);

        var staff = new Contractor(false);
    }
}

A Boolean Property

You can create a property of a Boolean type. To start, if you want to create a whole body for the property, first create a field that is of type bool. If necessary, add a constructor that uses a Boolean parameter. Of course, the property also must be a Boolean type. In the get accessor, return the Boolean field. In the set clause, assign the value contextual keyword to the Boolean field. Here is an example:

public class Member
{
    private bool isGood;

    public Member(bool status)
    {
        isGood = status;
    }

    public bool Accepted
    {
        get
        {
            return isGood;
        }
        set
        {
            isGood = value;
        }
    }
}

Once a Boolean read-write property exists, you can use it like any other. For example, you can assign a value to it or get the value it holds. Of course, the value you assign must be set as true or false. On the other hand, the value you retrieve is either true or false. Here are examples:

using System.Windows.Forms;

public class Member
{
    private bool isGood;

    /*public Member(bool status)
    {
        isGood = status;
    }*/

    public bool Accepted
    {
        get
        {
            return isGood;
        }
        set
        {
            isGood = value;
        }
    }
}

public class Membership
{
    private void Main()
    {
        bool applicationValidated = true;

        Member applicant = new Member();

        // Setting a value to the Boolean property
        applicant.Accepted = applicationValidated;

        Membership mbr = new Membership(applicant.Accepted);

        applicant.Accepted = false;

        // Getting the value of the Boolean property
        applicationValidated = applicant.Accepted;

        mbr = new Membership(applicant.Accepted);
    }
}

Of course, a Boolean property can also be created as an automatic property. Here is an example:

public class Member
{
    public bool Accepted { get; set; }

    /*public Member(bool status)
    {
        Accepted = status;
    }*/
}

Introduction to Web Controls

The Check Box

A check box is a control that allows a user to indicate something as being true or false. The user indicates this by checking the control. To support check boxes, HTML provides an attribute named checkbox. It created in an input tag.

Radio Buttons

A radio button is a small round control that allows a user to make a selection. A radio button usually comes as group with other radio buttons so that the user can select only one of them in the group. To let you create a radio button, the HTML provides an attribute named radio. It is used as a type in an input tag. To make sure that only one radio button can be selected from the group, all radio buttons in the group must hold the same name. Here is an example that creates a group of radio buttons:

<!DOCTYPE html>
<html>
<head>
<title>Department Sttore - Store Item</title>
</head>
<body>
<div align="center">
  <h2>Department Store - Store Item</h2>

  <form name="frmStoreItem" method="post">
    <table>
      <tr>
        <td>Small</td>
        <td><input type="radio" name="rdoLevel" /></td>
      </tr>
      <tr>
        <td>Medium</td>
        <td><input type="radio" name="rdoLevel" /></td>
      </tr>
      <tr>
        <td>Large</td>
        <td><input type="radio" name="rdoLevel" /></td>
      </tr>
    </table>
  </form>
</div>
</body>
</html>

This would produce:

Creating Radio Buttons

To select one of the radio buttons of a group, the user can click it.

Introduction to Logical Operators

A Logical Operator

A comparison is a Boolean operation that produces a true or a false result, depending on the values on which the comparison is performed. A comparison is performed between two values of the same type.

To let you perform comparisons and validations on values used in a webpage, you can use some symbols referred to as Boolean operators. The operator can be included between two operands as in:

operand1 operator operand2

This is referred to as a Boolean expression.

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:

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.

Initializing a Boolean Variable

In our introductions to Boolean values, we saw that, to initialize or specify the value of a Boolean variable, you can assign a true or false value. A Boolean variable can also be initialized with a Boolean expression. Here is an example:

public class Exercise
{
    private void Create()
    {
        bool employeeIsFullTime = position == "Manager";
    }
}

To make your code easy to read, you should include the logical expression in parentheses. This can be done as follows:

public class Exercise
{
    string GetEmployeePosition()
    {
        return "Associate Director";
    }

    public void Create()
    {
        string position = "";

        bool employeeIsFullTime = (position == "Manager");
    }
}

Introduction to Conditions

if an Operand is Equal to a Value

A conditional statement is a logical expression that produces a true or false result. You can then use that result as you want. To create a logical expression, you use a Boolean operator like the == operator we introduced above. To assist you with this, the C# language provides an operator named if. The formula to use it in a method of a class is:

if(condition) statement;

If you are using Microsoft Visual Studio, to create an if conditional statement, right-click the section where you want to add the code and click Code Snippet... Double-click Visual C#. In the list, double-click if:

if

To create an if expression in an HTML code, start it with the @ symbol as in:

@if(condition){
	statement;
}

The condition can be the type of Boolean operation we saw for the == operator. That is, the condition can have the following formula:

operand1 Boolean-operator operand2

Any of the operands can be a constant or the name of a variable. The operator can be == we saw earlier. The whole expression is the condition. If the expression produces a true result, then the statement would execute.

If you are working in a method of a class,. if the if statement is short, you can write it on the same line with the condition that is being checked. Here is an

If the statement is long, you can write it on a line different from that of the if condition.

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.

The Body of a Conditional Statement

Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket "{" and a closing curly bracket "}". This would be done as follows:

public class AmploymentApplication 
{
    if(employmentStatus == 1)
    {
        . . .
        . . .
        . . .
    }
}

Iif you are working the body of a method, if you omit the brackets, only the statement that immediately follows the condition would be executed. The section between the curly brackets is the body of the conditional statement.

If your code is written in the HTML code of a webpage, the if statement must have a body delimited by curly brackets.

if a Condition is True

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:

public class Exercise
{
    public void Create()
    {
        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:

public class Exercise
{
    public void Create()
    {
        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:

public class Exercise
{
    public void Create()
    {
        bool employeeIsFullTime = true;

        . . . No Change

        if( employeeIsFullTime)
        {

        }
    }
}

This would produce the same result as previously.

Introduction to Multiple Conditions

Just as you can create one if condition, you can write more than one to consider different outcomes of an expression or an object.

Practical LearningPractical Learning: Introducing Multiple Conditions

  1. Access the ElementsProcessing.cshtml file and create a helper as follows:
    @helper SelectElement(int number) {
        Chemistry06.App_Code.Element selected = new Chemistry06.App_Code.Element();
    
        Chemistry06.App_Code.Element h = new Chemistry06.App_Code.Element(1, "H", "Hydrogen", 1.008M) { Phase = Chemistry06.App_Code.Phase.Gas };
        Chemistry06.App_Code.Element he = new Chemistry06.App_Code.Element(2, "He", "Helium", 4.002602M) { Phase = Chemistry06.App_Code.Phase.Gas };
        Chemistry06.App_Code.Element li = new Chemistry06.App_Code.Element(3, "Li", "Lithium", 6.94M) { Phase = Chemistry06.App_Code.Phase.Solid };
        Chemistry06.App_Code.Element be = new Chemistry06.App_Code.Element(4, "Be", "Beryllium", 9.0121831M) { Phase = Chemistry06.App_Code.Phase.Solid };
        Chemistry06.App_Code.Element b = new Chemistry06.App_Code.Element(5, "B", "Boron", 10.81M) { Phase = Chemistry06.App_Code.Phase.Solid };
        Chemistry06.App_Code.Element c = new Chemistry06.App_Code.Element(name: "Carbon", mass: 12.011M, symbol: "C", number: 6) { Phase = Chemistry06.App_Code.Phase.Solid };
        Chemistry06.App_Code.Element n = new Chemistry06.App_Code.Element(7);
        n.Symbol = "N";
        n.AtomicWeight = 14.007M;
        n.ElementName = "Nitrogen";
        n.Phase = Chemistry06.App_Code.Phase.Gas;
    
        Chemistry06.App_Code.Element o = new Chemistry06.App_Code.Element("O")
        {
            AtomicNumber = 8,
            ElementName = "Oxygen",
            AtomicWeight = 15.999M,
            Phase = Chemistry06.App_Code.Phase.Gas
        };
        Chemistry06.App_Code.Element f = new Chemistry06.App_Code.Element("F")
        {
            AtomicNumber = 9,
            ElementName = "Fluorine",
            AtomicWeight = 15.999M,
            Phase = Chemistry06.App_Code.Phase.Gas
        };
        Chemistry06.App_Code.Element ne = new Chemistry06.App_Code.Element("Ne")
        {
            AtomicNumber = 10,
            ElementName = "Neon",
            AtomicWeight = 20.1797M,
            Phase = Chemistry06.App_Code.Phase.Gas
        };
        Chemistry06.App_Code.Element na = new Chemistry06.App_Code.Element(11, "Na", "Sodium", 22.98976928M) { Phase = Chemistry06.App_Code.Phase.Solid };
        Chemistry06.App_Code.Element mg = new Chemistry06.App_Code.Element(12, "Mg", "Magnesium", 24.305M) { Phase = Chemistry06.App_Code.Phase.Solid };
        Chemistry06.App_Code.Element al = new Chemistry06.App_Code.Element(13, "Al", "Aluminium", 26.9815385M) { Phase = Chemistry06.App_Code.Phase.Solid };
        
        if (number == 1) {
             selected = h;
        }
        if (number == 2)
        {
            selected = he; }
        if (number == 3)
        {
            selected = li;
        }
        if (number == 4) { selected = be; }
        if (number == 5) { selected = b; }
        if (number == 6) { selected = c; }
        if (number == 7) { selected = n; }
        if (number == 8) { selected = o; }
        if (number == 9) { selected = f; }
        if (number == 10) { selected = ne; }
        if (number == 11) { selected = na; }
        if (number == 12) { selected = mg; }
        if (number == 13) { selected = al; }
    
        <div class="container">
            <form name="frmChemistry" method="post">
                <table>
                    <tr>
                        <td class="emphasize left-col">Element Name:</td>
                        <td><input type="text" name="txtElementName" value=@selected.ElementName /></td>
                    </tr>
                    <tr>
                        <td class="emphasize">Symbol:</td>
                        <td><input type="text" name="txtSymbol" value=@selected.Symbol /></td>
                    </tr>
                    <tr>
                        <td class="emphasize">Atomic Weight:</td>
                        <td><input type="text" name="txtAtomicWeight" value=@selected.AtomicWeight /></td>
                    </tr>
                    <tr>
                        <td class="emphasize">Phase:</td>
                        <td><input type="text" name="txtAtomicWeight" value=@selected.Phase /></td>
                    </tr>
                </table>
            </form>
        </div>
    }
  2. In the Solution Explorer, right-click Chemistry06 -> Add -> New Item...
  3. In the left list, expand Web and click Razor
  4. In the middle list, click Web Page (Razor v3)
  5. Change the name to Index
  6. Click Add
  7. Change the code as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Chemistry</title>
    <link rel="stylesheet" type="text/css" href="~/Content/Site.css" />
    </head>
    <body>
    @{
        int number = 0;
    
        if (IsPost)
        {
            number = Request["txtAtomicNumber"].AsInt();
        }
    }
    
    <div id="top-banner">
        <p id="main-title">Chemistry</p>
    </div>
    
    <div class="title-holder">
        <div id="sub-title"></div>
        <hr />
    </div>
    
    <div class="item-selection">
            <form name="frmChemistry" method="post">
                <table>
                    <tr>
                        <td class="left-col emphasize">Atomic Number:</td>
                        <td>
                            <input type="text" name="txtAtomicNumber" class="small-text" value="@number" />
                            <input type="submit" name="btnFind" value="Find" style="width: 70px;" />
                        </td>
                    </tr>
                </table>
            </form>
    
        @ElementsProcessing.SelectElement(@number)
    </div>
    </body>
    </html>
  8. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Multiple Conditions

  9. In the text box, type a number between 1 (included) and 13 (included)
  10. Click the Find button:

    Introduction to Multiple Conditions

  11. Close the browser and close your programming environment
  12. Close your programming environment

Previous Copyright © 2001-2019, FunctionX Next