Lesson 13 - Comparison and Logical Operators

Tutorial Series: Free C# Fundamentals via ASP.NET Web Apps

Previous Article  |  Next Article


Get GitHub Code

In this lesson, we're going to delve deeper into comparison operators. We've already looked at the equivalence operator (==), which just tests whether or not two sides are equivalent to one another (whether that's two variables, two literal strings, two numbers, and so on). These other operators can also be used within a conditional’s parentheses for evaluation, but the rest of the evaluation process remains the same: it checks to see if the entire evaluated statement is true, or false.

Step 1: Create a New Project

To begin this Project, you may either create the Project from scratch or use the Before code in the provided code folder. If you choose to use the provided code, move ahead to Step 2, otherwise follow the steps below:

To demonstrate this, set up an ASP.NET project called “CS-ASP_013” and include the following Server Controls:

cs-asp-013---comparison-and-logical-operators.001

The programmatic IDs for these Controls are:

  1. firstTextBox

  2. comparisonTypeLabel

  3. secondTextBox

  4. checkedCheckBox

  5. okButton

  6. resultLabel

Step 2: Writing Code in the Page_Load Event

This time we’ll write some code in the Page_Load event, as well as the okButton_Click event:

cs-asp-013---comparison-and-logical-operators.002

When you run the application, notice how the comparisonTypeLabel is set as soon as the page loads:

cs-asp-013---comparison-and-logical-operators.003

Tip: Page_Load is an event, just like the okButton_Click is. Think of it this way: When the okButton is clicked an event occurs, and the code inside the code block runs. In the same way, as soon as the page loads, an event occurs and the code inside its code block executes. We'll discuss Page_Load in detail in a later lesson.

Step 3: List of Comparison Operators

Now turning to comparison operators, here is a list that includes the comparison being done as well as the types they operate on:

ComparisonOperators

Tip: Comparison operators imply that you are comparing two different things. As such, these are also referred to as binary operators, because they always operate on two different operands; one on each side of the operator.

Let’s test out these different comparison operators by modifying the code and running the application:

cs-asp-013---comparison-and-logical-operators.006

cs-asp-013---comparison-and-logical-operators.007

cs-asp-013---comparison-and-logical-operators.008

Now, try using the “greater-than” operator in the same way, and you will see that an error prevents us from moving forward. The problem is that we are attempting to use a mathematical comparison operator on string values:

cs-asp-013---comparison-and-logical-operators.009

The solution to this problem goes back to the conversion lesson that showed you how to convert a string to an int with the int.Parse() method:

cs-asp-013---comparison-and-logical-operators.010

When you run the application, you will now see that the comparison operator works as expected, provided that you only enter integer values:

cs-asp-013---comparison-and-logical-operators.011

cs-asp-013---comparison-and-logical-operators.012

Tip: It should be clear, at this point, how the rest of the mathematical comparison operators work. Just be sure to use >= and <= rather than =< or =>, when performing a greater-than-or-equal-to, or less-than-or-equal-to check. It’s easy to reverse them. And in the case of =>, it’s a totally different operator which is used for something called a lambda expression.

Step 4: Binary vs Unary Operators

So far we’ve been looking at the comparison operators that are said to be binary (meaning “two”) because they evaluate two different operands on opposite sides of the operator. However, there are also unary operators (meaning “one”) which are used to place an evaluation on a single operand. The most common unary operator, used within conditional expressions (although, not exclusively), is the single-exclamation operator, which can be read as saying “not.” You can place this operator on anything that evaluates to a bool, as follows:

cs-asp-013---comparison-and-logical-operators.014

This now evaluates as true only when it is not the case that checkedCheckBox.Checked is true. For this reason, we had to flip the resulting strings to accommodate this change and work as it did before:

cs-asp-013---comparison-and-logical-operators.015

Step 5: Compound Expressions in a Single Evaluation

You can also group expressions together to form more complex evaluations, using the “and” and “or” logical operators, which are also binary operators:

cs-asp-013---comparison-and-logical-operators.016

Here the && operator (representing “and”) is used to combine expressions to be evaluated within a single if() statement. This evaluation will only evaluate as true if:

  1. checkedCheckBox.Checked is true

  2. firstTextBox.Text == “Bob” is true

  3. secondTextBox.Text == “Tabor” is true

If any of those expressions individually evaluate as false, then the entire conditional statement evaluates as false. And, once again, don’t let the formatting fool you: these expressions were placed on separate lines only for the sake of visual clarity. Run the application and experiment with different combinations of bool evaluations:

cs-asp-013---comparison-and-logical-operators.017

cs-asp-013---comparison-and-logical-operators.018

We can be more flexible with the conditional evaluation by using the logical “or” operator, which is denoted by "||". Instead of requiring all of the code withing the conditional to evaluate as true, your code can execute if any of your conditions are met:

cs-asp-013---comparison-and-logical-operators.019

In this case, the conditional statement will evaluate as true if any of the three individual expressions evaluate as true:

cs-asp-013---comparison-and-logical-operators.020

cs-asp-013---comparison-and-logical-operators.021

cs-asp-013---comparison-and-logical-operators.022

Tip: It should be noted that more than one of these three expressions could evaluate true and the entire statement will evaluate as true. This is useful in cases where only certain conditions out of a set need to be met in order for your application to work. Think of optional input in a website's signup form. Your submission will go through whether you input only the required information or the required and optional information.

You can also combine the || and && operators together for more complex evaluations:

cs-asp-013---comparison-and-logical-operators.024

However, the && operator has precedence (just as multiplication/division has precedence in math) thereby grouping the comparison between firstTextBox.Text and secondTextBox.Text:

cs-asp-013---comparison-and-logical-operators.025

This is not the result we’re looking for, so let’s create our own precedence by wrapping the evaluation in parentheses, grouping the first comparison between checkedCheckBox.Checked and firstTextBox.Text. Now the entire statement evaluates as true only when, either, checkedCheckBox.Checked or firstTextBox.Text are true, and secondTextBox.Text is also true:

cs-asp-013---comparison-and-logical-operators.026

cs-asp-013---comparison-and-logical-operators.027

cs-asp-013---comparison-and-logical-operators.028

cs-asp-013---comparison-and-logical-operators.029

You can see from these examples the usefulness of comparison operators in your code. It allows you to further specify conditions that need to be met for your code to execute in order for the flow of your code to change. This will be very important and useful moving forward in this course, so do your best to review and make use of these concepts. You're doing great, keep it up!


Related Articles in this Tutorial:

Lesson 1 - Series Introduction

Lesson 2 - Installing Visual Studio 2015

Lesson 3 - Building Your First Web App

Lesson 4 - Understanding What You Just Did

Lesson 5 - Working with Projects in Visual Studio

Lesson 6 - Simple Web Page Formatting in Visual Studio

Challenge 1

Solution 1

Lesson 7 - Variables and Data Types

Lesson 8 - Data Type Conversion

Lesson 9 - Arithmetic Operators

Lesson 10 - C# Syntax Basics

Challenge 2 - ChallengeSimpleCalculator

Solution - ChallengeSimpleCalculator

Lesson 11 - Conditional If Statements

Lesson 12 - The Conditional Ternary Operator

Challenge 3 - ChallengeConditionalRadioButton

Solution - Challenge Conditional RadioButton

Lesson 13 - Comparison and Logical Operators

Lesson 13 Challenge - First Papa Bob's Website

Solution - Challenge First Papa Bob's Website

Lesson 14 - Working with Dates and Times

Lesson 15 - Working With Spans of Time

Lesson 16 - Working with the Calendar Server Control

Challenge 4 - Challenge Days Between Dates

Solution - Challenge Days Between Dates

Lesson 17 - Page_Load and Page.IsPostBack

Lesson 18 - Setting a Break Point and Debugging

Lesson 19 - Formatting Strings

Challenge 5 - Challenge Epic Spies Assignment

Solution - Challenge Epic Spies Assignment

Lesson 20 - Maintaining State with ViewState

Lesson 21 - Storing Values in Arrays

Lesson 22 - Understanding Multidimensional Arrays

Lesson 23 - Changing the Length of an Array

Challenge 6 - Challenge Epic Spies Asset Tracker

Solution - Challenge Epic Spies Asset Tracker

Lesson 24 - Understanding Variable Scope

Lesson 25 - Code Blocks and Nested If Statements

Lesson 26 - Looping with the For Iteration Statement

Challenge 7 - Challenge For Xmen Battle Count

Solution - Challenge For Xmen Battle Count

Lesson 27 - Looping with the while() & do...while() Iteration Statements

Lesson 28 - Creating and Calling Simple Helper Methods

Lesson 29 - Creating Methods with Input Parameters

Lesson 30 - Returning Values from Methods

Lesson 31 - Creating Overloaded Methods

Lesson 32 - Creating Optional Parameters

Lesson 33 - Creating Names Parameters

Lesson 34 - Creating Methods with Output Parameters

Challenge 8 - Challenge Postal Calculator Helper Methods

Solution - Challenge Postal Calculator Helper Methods

Mega Challenge Casino

Solution - Mega Challenge Casino

Lesson 35 - Manipulating Strings

Challenge 9 - Phun With Strings

Solution - Challenge Phun With Strings

Lesson 36 - Introduction to Classes and Objects

Challenge - Hero Monster Classes Part 1

Solution - Hero Monster Classes Part 1

Challenge - Hero Monster Classes Part 2

Solution - Challenge Hero Monster Classes Part 2

Lesson 37 - Creating Class Files Creating Cohesive Classes and Code Navigation

Lesson 38 - Understanding Object References and Object Lifetime

Lesson 39 - Understanding the .NET Framework and Compilation

Lesson 40 - Namespaces and Using Directives

Lesson 41 - Creating Class Libraries and Adding References to Assemblies

Lesson 42 - Accessibility Modifiers, Fields and Properties

Lesson 43 - Creating Constructor Methods

Lesson 44 - Naming Conventions for Identifiers

Lesson 45 - Static vs Instance Members

Challenge 10 - Challenge Simple Darts

Solution - Challenge Simple Darts

Lesson 46 - Working with the List Collection

Lesson 47 - Object Initializers

Lesson 48 - Collection Initializers

Lesson 49 - Working with the Dictionary Collection

Lesson 50 - Looping with the foreach Iteration Statement

Lesson 51 - Implicitly-Typed Variables with the var Keyword

Challenge 11 - Challenge Student Courses

Solution - Challenge Student Courses

Mega Challenge War

Solution - Mega Challenge War

Lesson 52 - Creating GUIDs

Lesson 53 - Working with Enumerations

Lesson 54 - Understanding the switch() Statement

Lesson 55 - First Pass at the Separation of Concerns Principle

Lesson 56 - Understanding Exception Handling

Lesson 57 - Understanding Global Exception Handling

Lesson 58 - Understanding Custom Exceptions

Lesson 59 - Creating a Database in Visual Studio

Lesson 60 - Creating an Entity Data Model

Lesson 61 - Displaying the DbSet Result in an ASP.NET GridView

Lesson 62 - Implementing a Button Command in a GridView

Lesson 63 - Using a Tools-Centric Approach to Building a Database Application

Lesson 64 - Using a Maintenance-Driven Approach to Building a Database Application

Lesson 65 - Creating a New Instance of an Entity and Persisting it to the Database

Lesson 66 - Package Management with NuGet

Lesson 67 - NuGet No-Commit Workflow

Lesson 68 - Introduction the Twitter Bootstrap CSS Framework

Lesson 69 - Mapping Enum Types to Entity Properties in the Framework Designer

Lesson 70 - Deploying the App to Microsoft Azure Web Services Web Apps

Papa Bob's Mega Challenge

Papa Bob's Mega Solution Part 1 - Setting up the Solution

Papa Bob's Mega Solution Part 2 - Adding an Order to the Database

Papa Bob's Mega Solution Part 3 - Passing an Order from the Presentation Layer

Papa Bob's Mega Solution Part 4 - Creating the Order Form

Papa Bob's Mega Solution Part 5 - Adding Enums

Papa Bob's Mega Solution Part 6 - Creating an Order with Validation

Papa Bob's Mega Solution Part 7 - Calculating the Order Price

Papa Bob's Mega Solution Part 8 - Displaying the Price to the User

Papa Bob's Mega Solution Part 9 - Creating the Order Management Page


Comments

Please login or register to add a comment