Home

Introduction to Conditions

   

Boolean Variables

 

Introduction

When interacting with a computer, a user submits values to a running application. Some of these values are valid. Some other values must be rejected or changed. To take care of these, the values must be checked, examined, re-examined, etc. The validity of a value is checked against its type. For example, a number can be checked as being equal to another. A condition can be checked as being true. A measure can be checked as to whether it is higher than a certain threshold.

 

To perform the necessary validations of values, the C# language provides some symbols, referred to as Boolean operators.

ApplicationApplication: Introducing Boolean Variables

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Empty Project
  4. Change the Name to NationalBank2 and press Enter
  5. To create a new file, in the Solution Explorer, right-click NationalBank2 -> Add -> New Item...
  6. In the middle list, click Code File
  7. Change the Name of the file to Employee
  8. Click Add
  9. Complete the Employee.cs file as follows:
     public class Employee
    {
        public string EmployeeNumber;
        public string FirstName;
        public string LastName;
        public double HourlySalary;
    
        public Employee(string emplNbr = "00-000", string fName = "John",
                        string lName = "Doe", double salary = 0.00)
        {
            EmployeeNumber = emplNbr;
            FirstName = fName;
            LastName = lName;
            HourlySalary = salary;
        }
    }
  10. To create a new file, in the Solution Explorer, right-click NationalBank2 -> Add -> New Item...
  11. In the middle list, make sure Code File is selected.
    Change the Name to Management and press Enter
  12. Complete the file as follows:
    using System;
    
    public class Management
    {
        private  static Employee HireEmployee()
        {
            Employee empl = new Employee();
    
            Console.Title = "National Bank";
            Console.WriteLine("=======================");
            Console.WriteLine("==-= National Bank =-==");
       Console.WriteLine("To hire a new employee, enter the following information");
            Console.WriteLine("-----------------------");
            Console.Write("Employee #:    ");
            empl.EmployeeNumber = Console.ReadLine();
            Console.Write("First Name:    ");
            empl.FirstName = Console.ReadLine();
            Console.Write("Last Name:     ");
            empl.LastName = Console.ReadLine();
            Console.Write("Hourly Salary: ");
            empl.HourlySalary = double.Parse(Console.ReadLine());
            Console.WriteLine("=======================");
    
            return empl;
        }
    
        private static void ShowEmployeeRecord(Employee empl)
        {
            Console.Title = "National Bank";
            Console.WriteLine("=======================");
            Console.WriteLine("==-= National Bank =-==");
            Console.WriteLine("    Employee Record");
            Console.WriteLine("-----------------------");
            Console.WriteLine("Employee #:    {0}", empl.EmployeeNumber);
            Console.WriteLine("First Name:    {0}", empl.FirstName);
            Console.WriteLine("Last Name:     {0}", empl.LastName);
            Console.WriteLine("Hourly Salary: {0}", empl.HourlySalary);
            Console.WriteLine("=======================");
        }
    
        public static int Main()
        {
            Employee clerk = null ;
    
            clerk = HireEmployee();
            Console.Clear();
            ShowEmployeeRecord(clerk);
    
            Console.ReadKey();
            return 0;
        }
    }
  13. To execute the application, on the main menu, click Debug -> Start Debugging
  14. Enter information as follows:
     
    Employee # 88-602
    First Name Joan
    Last Name Gergman
    Hourly Salary 16.85
  15. Press Enter
    =======================
    ==-= National Bank =-==
        Employee Record
    -----------------------
    Employee #:    88-602
    First Name:    Joan
    Last Name:     Bergman
    Hourly Salary: 16.85
    =======================
  16. Press Enter to close the DOS window

Declaring a Boolean Variable

A variable is referred to as Boolean if it can hold a value that is either true or false. To declare a Boolean variable, you can use either the var or the bool keyword. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        bool drinkingUnderAge;

	return 0;
    }
}

Alternatively, you can declare a Boolean variable using the Boolean data type. The Boolean data type is part of the System namespace. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        bool drinkingUnderAge;
    	Boolean theFloorIsCoveredWithCarpet;

	return 0
    }
}

After the variable has been declared, you must initialize it with a true or a false value. In fact, if you declare it as var, you must initialize it. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var drinkingUnderAge = true;

        return 0;
    }
}

To display the value of a Boolean variable on the console, you can type its name in the parentheses of the Write() or the WriteLine() methods of the Console class. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var drinkingUnderAge = true;

        Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
        return 0;
    }
}

This would produce:

Drinking Under Age: True
Press any key to continue . . .

At any time and when you judge it necessary, you can change the value of the Boolean variable by assigning it a true or false value. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var drinkingUnderAge = true;

        Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);

        drinkingUnderAge = false;
        Console.WriteLine("Drinking Under Age: {0}", drinkingUnderAge);
        return 0;
    }
}

This would produce:

Drinking Under Age: True
Drinking Under Age: False
Press any key to continue . . .

Retrieving the Value of a Boolean Variable

As reviewed for the other data types, you can request the value of a Boolean variable from the user. In this case, the user must type either True (or true) or False (or false) and you can retrieve it using the Read() or the ReadLine() methods of the Console class. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        var drivingUnderAge = false;

        Console.WriteLine("Were you driving under age?");
        Console.Write("If Yes, enter True. Otherwise enter False: ");
        drivingUnderAge = bool.Parse(Console.ReadLine());

        Console.WriteLine("\nWas Driving Under Age: {0}\n", drivingUnderAge);
        return 0;
    }
}

Here is an example of running the program:

Were you driving under age?
If Yes, enter True. Otherwise enter False: true

Was Driving Under Age: True

Press any key to continue . . .

Creating 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. You declare it like any other variable, using the bool keyword or the Boolean data type. Here is an example:

public class House
{
    char typeOfHome;
    int beds;
    float baths;
    byte stories;
    bool hasCarGarage;
    int yearBuilt;
    double value;
}

When initializing an object that has a Boolean variable as a member, simply assign true or false to the variable. In the same way, you can retrieve or check the value that a Boolean member variable is holding by simply accessing it. Here are examples:

using System;

public class House
{
    public char typeOfHome;
    public int beds;
    public float baths;
    public byte stories;
    public bool hasCarGarage;
    public int yearBuilt;
    public double value;
}

public class Program
{
    static int Main()
    {
        var Condominium = new
        {
            hasCarGarage = false,
            yearBuilt = 2002,
            baths = 1.5F,
            stories = 18,
            value = 155825,
            beds = 2,
            typeOfHome = 'C'
        };

        Console.WriteLine("=//= Altair Realtors =//=");
        Console.WriteLine("=== Property Listing ===");
        Console.WriteLine("Type of Home:        {0}", Condominium.typeOfHome);
        Console.WriteLine("Number of Bedrooms:  {0}", Condominium.beds);
        Console.WriteLine("Number of Bathrooms: {0}", Condominium.baths);
        Console.WriteLine("Number of Stories:   {0}", Condominium.stories);
        Console.WriteLine("Year Built:          {0}", Condominium.yearBuilt);
        Console.WriteLine("Has Car Garage:      {0}", Condominium.hasCarGarage);
        Console.WriteLine("Monetary Value:      {0}\n", Condominium.value);

        return 0;
    }
}

This would produce:

=//= Altair Realtors =//=
=== Property Listing ===
Type of Home:        C
Number of Bedrooms:  2
Number of Bathrooms: 1.5
Number of Stories:   18
Year Built:          2002
Has Car Garage:      False
Monetary Value:      155825

Press any key to continue . . .

Boolean Arguments

Like parameters of the other types, you can pass an argument of type bool or Boolean to a method. Such an argument would be treated as holding a true or false value.

Enumerations

 

Introduction

Consider that, when creating a program for a real estate company that sells houses, you want the program to ask a customer the type of house that he or she wants to purchase and/or the type of garage that the desired house should have. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
        int typeOfHouse = 0;
        int typeOfGarage = 0;

        Console.WriteLine("Enter the type of house you want to purchase");
        Console.WriteLine("1 - Single Family");
        Console.WriteLine("2 - Townhouse");
        Console.WriteLine("3 - Condominium");
        Console.Write("Your Choice: ");
        typeOfHouse = int.Parse(Console.ReadLine());

        Console.WriteLine("Enter the type of garage you want");
        Console.WriteLine("0 - Doesn't matter");
        Console.WriteLine("1 - Interior");
        Console.WriteLine("2 - Exterior");
        Console.Write("Your Choice: ");
        typeOfGarage = int.Parse(Console.ReadLine());

	Console.Clear();

        Console.WriteLine("\nHouse Type: {0}", typeOfHouse);
        Console.WriteLine("Garage Type:  {0}", typeOfGarage);

        return 0;
    }
}

Here is an example of running the program:

Enter the type of house you want to purchase
1 - Single Family
2 - Townhouse
3 - Condominium
Your Choice: 3
Enter the type of garage you want
0 - Doesn't matter
1 - Interior
2 - Exterior
Your Choice: 1
---------------------------------------------------
House Type:  3
Garage Type: 1
Press any key to continue . . .

For such a program, the numbers can be vague. 1 can be considered a general number but, in our program, it can represent a Single Family house or an Interior type of garage. At the same time, our program uses the constant 1 in particular meaningful ways. To make it possible to give more meaning to a constant number, when the number can be made part of a series, C# allows you to create a type of list.

An enumeration is a series of constant integers that each has a specific position in the list and can be recognized by a meaningful name. Based on this, instead of just remembering that the constant 1 represents Single Family, you can create a list that has that type of house. In another list, instead of using 1 again, you can give it a name. Consequently, in each list, although the constant 1 would still be considered, at least it would mean something precise.

Creating an Enumeration

To create an enumeration, you use the enum keyword, followed by the name of the enumeration, followed by a name for each item of the list. The name of the enumerator and the name of each item of the list follows the rules we reviewed for names. The formula of creating an enumeration is:

enum Enumeration_Name {Item1, Item2, Item_n};

To create an enumeration, you can manually type the code. To use a code snippet, right-click where you want to add the enumeration and click Insert Snippet... Double-click Visual C#. In the list, double-click enum:

Enum

Here is an example of creating an enumeration:

using System;

public class Exercise
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        return 0;
    }
}

Declaring an Enumeration Variable

After creating an enumeration, each member of the enumeration holds a value of a natural number, such as 0, 4, 12, 25, etc. In C#, an enumeration cannot hold character values (of type char).

After creating an enumeration, you can declare a variable from it. Here is an example:

using System;

public class Exercise
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        HouseType propType;

        return 0;
    }
}

Just as done with the other types, you can use the var keyword to declare a variable of an enumeration type.

Initializing an Enumeration Variable

After declaring a variable for an enumeration, to initialize it, specify which member of the enumeration would be assigned to the variable. You should only assign a known member of the enumeration. To do this, on the right side of the assignment operator, type the name of the enumeration, followed by the period operator, and followed by the member whose value you want to assign. Here is an example:

using System;

public class Exercise
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        var propType = HouseType.SingleFamily;

        return 0;
    }
}

You can also find out what value the declared variable is currently holding. For example, you can display it on the console using Write() or WriteLine(). Here is an example:

using System;

public class Exercise
{
    enum HouseType { Unknown, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        var propType = HouseType.SingleFamily;

        Console.WriteLine("House Type:  {0}", propType);

        return 0;
    }
}

This would produce:

House Type:  SingleFamily
Press any key to continue . . .

An enumeration is in fact a list of numbers where each member of the list is identified with a name. By default, the first item of the list has a value of 0, the second has a value of 1, and so on. For example, on the HouseType enumeration, Unknown has a value of 0 while Townhouse has a value of 2. These are the default values. If you don't want these values, you can specify the value of one or each member of the list. Suppose you want the Unknown member in the above enumeration to have a value of 5. To do this, use the assignment operator "=" to give the desired value. The enumerator would be:

using System;

public class Exercise
{
    enum HouseType { Unknown = 5, SingleFamily, TownHouse, Condominium }
    
    static int Main()
    {
        return 0;
    }
}

In this case, Unknown now would have a value of 5, SingleFamily would have a value of 6 because it follows a member whose value is 1 (thus 5 + 1 = 6). Townhouse would have a value of 7, and Condominium would have a value of 8. You can also assign a value to more than one member of an enumeration. Here is an example:

using System;

public class Exercise
{
    enum HouseType { Unknown = 3, SingleFamily = 12, TownHouse, Condominium = 8 }
    
    static int Main()
    {
        return 0;
    }
}

In this case, Townhouse would have a value of 13 because it follows SingleFamily that has a value of 12.

Enumerations Visibility

By default, if you create an enumeration the way we have proceeded so far, it would be available only in the project it belongs to. As done for a class, you can control an enumeration's accessibility outside of its project. This means that you can hide or make it visible outside of its project. To do this, you can precede it with the private or the public keyword. Here is an example:

using System;

public class Exercise
{
    public enum HouseType
    {
        Unknown,
        SingleFamily,
        TownHouse,
        Condominium
    }
    
    static int Main()
    {
        HouseType propType = HouseType.SingleFamily;

        Console.WriteLine("House Type:  {0}", propType);
        return 0;
    }
}

An Enumeration as a Member Variable

After creating an enumeration, you can use it as a data type to declare a variable. To create a field that is of an enumeration type, follow the same rules as done for the primitive types: the name of the enumeration, followed by the name of the variable, and followed by a semi-colon. Here is an example:

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}

public class House
{
    HouseType propertyType;
}

In the same way, you can declare as many enumeration variables as you want. After declaring the variable, to initialize it, assign it the desired member of the enumeration. Here is an example:

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}

public class House
{
    HouseType propertyType;

    public House()
    {
        propertyType = HouseType.Unknown;
    }
}

Once the member variable has been initialized, you can use it as you see fit as we will learn and practice in future sections and lessons. At a minimum, you can pass it to Write() or WriteLine() to display its value. Here is an example:

using System;

public enum HouseType
{
    Unknown,
    SingleFamily,
    TownHouse,
    Condominium
}

public class House
{
    public HouseType propertyType;

    public House()
    {
        propertyType = HouseType.Unknown;
    }

    public void Display()
    {
        Console.WriteLine("Property Type: {0}", propertyType);
    }
}

public class Exercise
{
    static int Main()
    {
        var propType = new House();
        propType.Display();
        Console.WriteLine();

        propType.propertyType = HouseType.SingleFamily;
        propType.Display();
        Console.WriteLine();

        return 0;
    }
}

This would produce:

Property Type: Unknown

Property Type: SingleFamily

Press any key to continue . . .

Using it as normal data type, you can create a method that returns an enumeration. You can also pass an enumeration to a method as argument.

Passing an Enumeration as Argument

As mentioned already, once an enumeration has been created, it becomes a type. It can be passed as argument and/or it can be returned from a method.

You pass an enumeration as argument using the same approach of a normal data type. Here is an example:

public class Exercise
{
    private static void ShowHouse(HouseType propType)
    {

    }
}

In the same way, you can pass as many enumeration types as necessary. In the body of the procedure, you can use the enumeration or ignore it. When calling the procedure, pass an argument that holds a value of the type of enumeration. Here is an example:

using System;

public enum HouseType
{
    Unknown = 2,
    SingleFamily = 4,
    TownHouse = 6,
    Condominium = 8,
}

public class Exercise
{
    private static void ShowHouse(HouseType propType)
    {
        Console.WriteLine("Type of house: {0}", propType);
    }

    public static int Main()
    {
        HouseType ht;

        ht = HouseType.SingleFamily;
        ShowHouse(ht);

        Console.ReadKey();
        return 0;
    }
}

This would produce:

Type of house: SingleFamily
Press any key to continue . . .

You can also pass the argument as optional. When creating a method, use the assignment operator to specify that the argument has a default value and assign the desired member of the enumeration. When calling the method, you can pass, or omit passing, a value for the argument. Here is an example:

using System;

public enum HouseType
{
    Unknown = 2,
    SingleFamily = 4,
    TownHouse = 6,
    Condominium = 8,
}

public class Exercise
{
    private static void ShowHouse(HouseType propType = HouseType.Unknown)
    {
        Console.WriteLine("Type of house: {0}", propType);
    }

    public static int Main()
    {
        HouseType ht;

        ht = HouseType.SingleFamily;
        ShowHouse();
        return 0;
    }
}

This would produce:

Type of house: Unknown
Press any key to continue . . .

ApplicationApplication: Creating and Using an Enumeration

  1. Access the Employee.cs file
  2. To create some enumerations, change the file as follows:
     public enum EmploymentStatus
    {
        FullTime,
        PartTime,
        Internship,
        Unknown
    }
    
    public class Employee
    {
            public string EmployeeNumber;
            public string FirstName;
            public string LastName;
            public string Title;
            public double HourlySalary;
            public EmploymentStatus Status;
    
            public Employee(string emplNbr = "00-000", string fName = "John",
                            string lName = "Doe", string function = "Temporary",
                            double salary = 0.00,
                            EmploymentStatus emplStatus = EmploymentStatus.Unknown)
            {
                EmployeeNumber = emplNbr;
                FirstName = fName;
                LastName = lName;
                Title = function;
                HourlySalary = salary;
                Status = emplStatus;
            }
    }
  3. Access the Management.cs file
  4. To use an enumeration, change the file as follows:
    using System;
    
    public class Management
    {
        private static Employee HireEmployee()
        {
            int? status = null;
            Employee empl = new Employee();
    
            Console.Title = "National Bank";
            Console.WriteLine("=======================================");
            Console.WriteLine("==-= National Bank =-==");
      Console.WriteLine("To hire a new employee, enter the following information");
            Console.WriteLine("---------------------------------------");
            Console.Write("Employee #:    ");
            empl.EmployeeNumber = Console.ReadLine();
            Console.Write("First Name:    ");
            empl.FirstName = Console.ReadLine();
            Console.Write("Last Name:     ");
            empl.LastName = Console.ReadLine();
            Console.Write("Title:         ");
            empl.Title = Console.ReadLine();
            Console.Write("Hourly Salary: ");
            empl.HourlySalary = double.Parse(Console.ReadLine());
            Console.WriteLine("Employment Status");
            Console.WriteLine("1. Full-Time");
            Console.WriteLine("2. Part-Time");
            Console.WriteLine("3. Intern");
            Console.Write("Your Choice? ");
            Status = int.Parse(Console.ReadLine());
            empl.status = (EmploymentStatus)(status - 1);
            Console.WriteLine("=======================================");
            
            return empl;
        }
    
        private static void ShowEmployeeRecord(Employee empl)
        {
            Console.Title = "National Bank";
            Console.WriteLine("=======================================");
            Console.WriteLine("==-= National Bank =-==");
            Console.WriteLine("    Employee Record");
            Console.WriteLine("---------------------------------------");
            Console.WriteLine("Employee #:        {0}", empl.EmployeeNumber);
            Console.WriteLine("First Name:        {0}", empl.FirstName);
            Console.WriteLine("Last Name:         {0}", empl.LastName);
            Console.WriteLine("Employee Title:    {0}", empl.Title);
            Console.WriteLine("Hourly Salary:     {0}", empl.HourlySalary);
            Console.WriteLine("Employment Status: {0}", empl.Status);
            Console.WriteLine("=======================================");
        }
    
        public static int Main()
        {
            Employee clerk = null ;
    
            clerk = HireEmployee();
            Console.Clear();
            ShowEmployeeRecord(clerk);
    
            Console.ReadKey();
            return 0;
        }
    }
  5. To execute the application, press F5
  6. Enter information as follows:
     
    Employee # 42-855
    First Name Paula
    Last Name Meyer
    Title Cashier
    Hourly Salary 18.25
    Employment Status 2
    =======================================
    ==-= National Bank =-==
    To hire a new employee, enter the following information
    ---------------------------------------
    Employee #:    42-855
    First Name:    Paula
    Last Name:     Meyer
    Title:         Cashier
    Hourly Salary: 18.25
    Employment Status
    1. Full-Time
    2. Part-Time
    3. Intern
    Your Choice? 2
  7. Press Enter
    =======================================
    ==-= National Bank =-==
        Employee Record
    ---------------------------------------
    Employee #:        42-855
    First Name:        Paula
    Last Name:         Meyer
    Employee Title:    Cashier
    Hourly Salary:     18.25
    Employment Status: PartTime
    =======================================
  8. Press Enter to close the DOS window and return to your programming environment

Returning an Enumeration From a Method

To create a method that returns an enumeration, specify its return type as the name of the enumeration. In the body of the enumeration, do whatever you have to do. Before exiting the method, make sure you return a value that is the type of the enumeration. Here is an example:

public class Exercise
{
    private HouseType SpecifyPropertyType()
    {
        HouseType pt;

        pt = HouseType.TownHouse;
        return pt;
    }
}

You can call a method that returns an enumeration type by using just its name. Otherwise, you can use its returned value. Here is an example:

using System;

public enum HouseType
{
    Unknown = 2,
    SingleFamily = 4,
    TownHouse = 6,
    Condominium = 8,
}

public class Exercise
{
    private static void ShowHouse(HouseType propType = HouseType.Unknown)
    {
        Console.WriteLine("Type of house: {0}", propType);
    }

    private static HouseType SpecifyPropertyType()
    {
        HouseType pt;

        pt = HouseType.TownHouse;
        return pt;
    }

    public static int Main()
    {
        HouseType ht;

        ht = SpecifyPropertyType();
        ShowHouse(ht);
        return 0;
    }
}

This would produce:

Type of house: TownHouse
Press any key to continue . . .

Logical Operators

 

Introduction

A program is a series of instructions that ask the computer (actually the compiler) to check some situations and to act accordingly. To check such situations, the computer spends a great deal of its time performing comparisons between values. 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; for example, you can compare two numbers, two characters, or the names of two cities. On the other hand, a comparison between two disparate values doesn't bear any meaning. For example, it is difficult to compare a telephone number and somebody's age, or a music category and the distance between two points. Like the binary arithmetic operations, the comparison operations are performed on two values. Unlike arithmetic operations where results are varied, a comparison produces only one of two results. The result can be a logical true or a logical false. When a comparison is true, it has an integral value of 1 or positive; that is, a value greater than 0. If the comparison is not true, it is considered false and carries an integral value of 0.

The C# language is equipped with various operators used to perform any type of comparison between similar values. The values could be numeric, strings, or objects (operations on objects are customized in a process referred to as Operator Overloading).

There are primary assumptions you should make when writing statements used in conditions:

  • Simplicity and Clarity: A statement should be clear enough and possibly simple but as complete as possible. When a statement becomes long, it can lead to being segmented in short parts, which deceives its clarity and may create other issues.
  • Factual: The statement must be presented as fact and not as opinion. This means that you don't have to like the statement but the majority, including you, must agree that it is true or it is false. In fact, the statement doesn't have to be correct but it must be agreed upon to be true. Based on this, a statement such as "An hour contains 45 minutes" doesn't have to fit your way of thinking but it must be considered as true or as false. A statement such as "This job applicant is attractive" is an opinion and therefore must not be considered in a conditional statement.
  • Circumstantial Truthfulness: At the time the statement is made, it must be considered as true or as false even if it can change at another time. For example, suppose that, in a certain year, a statement is formulated as "This year, the month of February has 28 days". Although allowed, you should refrain from regularly using circumstantial truthfulness, unless you have to.
  • Inverse: A statement must be able to find its reverse. This means that, when a statement is made and decided upon to be true or false, an inverse statement must be found to make it false or true. For example, if you have a statement such as "This job applicant is 18 years old", you must be able to state that "This job applicant is not 18 years old" or "This job applicant is younger than 18".

In your programs, make sure you clearly formulate your statements. This would make your programs easy to read and troubleshoot when problems occur (not if, but when).

The Equality Operator ==

To compare two variables for equality, C# uses the == operator. The formula used is:

value1 == Value2

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false.

Most of the comparisons performed in C# will be applied to conditional statements. The result of a comparison can also be assigned to a variable. To store the result of a comparison, you should include the comparison operation between parentheses. Here is an example:

using System;

public class Exercise
{
    static int Main()
    {
	var value1 = 15;
	var value2 = 24;

	Console.Write("Value 1 = ");
	Console.WriteLine(value1);
	Console.Write("Value 2 = ");
	Console.WriteLine(value2);
	Console.Write("Comparison of value1 == 15 produces ");
	Console.WriteLine(value1 == 15);

        return 0;
    }
}

This would produce:

Value 1 = 15
Value 2 = 24
Comparison of value1 == 15 produces True

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 to values. The operands on both sides of == can be variables, constants, or one can be a variable while the other is a constant. If you use one operator in place of the other, you would receive an error when you compile the program.

The Logical Not Operator !

When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. C# considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is:

!Value

There are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator 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:

using System;

public class Exercise
{
    static int Main()
    {
	bool hasAirCondition = true;
	bool doesIt;

	Console.Write("hasAirCondition = ");
	Console.WriteLine(hasAirCondition);
	doesIt = !hasAirCondition;
	Console.Write("doesIt          = ");
	Console.WriteLine(doesIt);

        return 0;
    }
}

This would produce:

hasAirCondition = True
doesIt          = False

When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it.

Less Than: <

To find out whether one value is lower than another, use the < operator. Its syntax is:

Value1 < Value2

Flowchart: Less Than

Less Than of 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 is less than the second. 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 VBalue2 hold the same value, 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.

Less Than Or Equal

Greater Than or Equal To: >

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:

Greater Than

 

The Greater Than or Equal Operator >=

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. Its syntax is:

Value1 >= Value2

A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand,, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result:

Flowchart: Greater Than Or Equal To

Here is a summary table of the logical operators we have studied:

 
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 <
 

ApplicationApplication: Ending the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click No
 
 

Previous Copyright © 2010-2016, FunctionX Next