Skip to content

Chapter 6: Making Decisions - Booleans, Comparison, and 'if/else'

Theoretical Foundations

A boolean is a data type that can only hold one of two possible values: true or false. It is the absolute foundation of decision-making in programming. Without booleans, a computer program would execute every line of code in sequence, with no ability to react to input, validate data, or choose different paths.

In the context of building AI applications, booleans are the fundamental switch that controls logic. For example, before an AI model generates a response, a boolean check might verify if the user's input is within the allowed length. If it is, the boolean is true, and the program proceeds to call the AI API. If it is not, the boolean is false, and the program might display an error message instead. Every "if-then" rule in an AI system's logic is built upon the evaluation of a boolean expression.

The Boolean Data Type

As introduced in Chapter 2: Variables, we declare a variable using a specific type. For a boolean, we use the bool keyword.

// Declaring a boolean variable to track if a user is logged in
bool isUserLoggedIn = true;

// Declaring a boolean variable to track if a transaction is valid
bool isTransactionValid = false;

Naming Conventions: Notice the naming pattern isSomething, hasSomething, or canDoSomething. This is a standard convention in C# for boolean variables. It makes the code read like an English sentence. When you later see if (isUserLoggedIn), it is immediately clear what condition is being checked.

Comparison Operators: Creating Booleans

Booleans are rarely static values like true or false assigned manually. Instead, they are usually the result of a comparison. Comparison operators look at two values and return a boolean based on their relationship.

Chapter 4: Arithmetic introduced mathematical operators (+, -, *, /). Comparison operators look similar but serve a different purpose: they do not calculate a new number; they ask a question that results in true or false.

1. Equality (==)

The double equals sign checks if two values are exactly the same.

  • 5 == 5 results in true.
  • 5 == 3 results in false.
  • "Hello" == "Hello" results in true.

Critical Distinction:

  • = (Single Equals): Assignment operator (sets a value).
  • == (Double Equals): Comparison operator (checks equality).
int currentScore = 100;
int targetScore = 100;

// This checks if currentScore equals targetScore
bool isScoreMatch = (currentScore == targetScore); // Result: true

2. Inequality (!=)

The exclamation mark combined with equals checks if two values are not the same.

  • 5 != 5 results in false.
  • 5 != 3 results in true.
string userRole = "Guest";
string adminRole = "Admin";

// Checking if the user is NOT an admin
bool isNotAdmin = (userRole != adminRole); // Result: true

3. Greater Than (>) and Less Than (<)

These operators compare numerical magnitudes.

  • > : Is the left value larger than the right?
  • < : Is the left value smaller than the right?
int age = 25;
int minimumAge = 18;

// Is the user old enough?
bool isOldEnough = (age >= minimumAge); // Result: true

4. Greater Than or Equal To (>=) and Less Than or Equal To (<=)

These combine equality and magnitude comparison.

  • >= : Is the left value larger than or equal to the right?
  • <= : Is the left value smaller than or equal to the right?

The Logic of Control: if, else if, and else

Once we have a boolean expression (a statement that evaluates to true or false), we need a way to act on that result. This is where control flow statements come in.

The if Statement

The if statement checks a condition. If the condition is true, the code block inside the curly braces {} executes. If the condition is false, the code block is skipped entirely.

Syntax:

if (boolean_expression)
{
    // Code to execute if the expression is true
}

Real-World Analogy: Imagine a smart home light switch with a motion sensor. The logic is: "If motion is detected (true), turn on the light." If no motion is detected (false), do nothing.

Code Example:

using System;

class Program
{
    static void Main()
    {
        // We use Console.ReadLine (Chapter 5) to get user input
        Console.Write("Enter your age: ");
        string input = Console.ReadLine();

        // We convert the string input to an integer (Chapter 5)
        int age = int.Parse(input);

        // We create a boolean expression using a comparison operator
        if (age >= 18)
        {
            // This block only runs if age is 18 or higher
            Console.WriteLine("Access Granted: Welcome to the adult section.");
        }
    }
}

The else Statement

The else statement provides a fallback path. It defines code to execute only if the preceding if condition was false. An else does not have a condition in parentheses; it is the default "catch-all" for a specific if.

Syntax:

if (boolean_expression)
{
    // Code if true
}
else
{
    // Code if false
}

Analogy: Returning to the smart home light: "If motion is detected, turn on the light. Else (if no motion is detected), keep the light off."

Code Example:

using System;

class Program
{
    static void Main()
    {
        Console.Write("Do you have a valid ticket? (yes/no): ");
        string answer = Console.ReadLine();

        // Note: We are comparing strings here.
        // String comparison is case-sensitive by default in C#.
        if (answer == "yes")
        {
            Console.WriteLine("Please enter the venue.");
        }
        else
        {
            // This runs only if answer is NOT "yes"
            Console.WriteLine("Sorry, you cannot enter without a ticket.");
        }
    }
}

The else if Statement

What if you have more than two possibilities? You can chain else if between an if and an else. This allows you to check multiple distinct conditions sequentially.

Execution Flow:

  1. Check if condition. If true, run that block and skip the rest.
  2. If false, check the next else if condition. If true, run that block and skip the rest.
  3. If all previous conditions are false, run the else block (if it exists).

Analogy: A grading system:

  • If score >= 90, print "A".
  • Else if score >= 80, print "B".
  • Else if score >= 70, print "C".
  • Else, print "F".

Code Example:

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter your current subscription level (Basic/Pro/Enterprise): ");
        string level = Console.ReadLine();

        if (level == "Enterprise")
        {
            Console.WriteLine("Welcome! You have unlimited access.");
        }
        else if (level == "Pro")
        {
            Console.WriteLine("Welcome! You have standard access.");
        }
        else if (level == "Basic")
        {
            Console.WriteLine("Welcome! You have limited access.");
        }
        else
        {
            // Handles "Free", "Guest", or any invalid input
            Console.WriteLine("Please create an account to get started.");
        }
    }
}

Logical Operators: Combining Booleans

Sometimes a single comparison isn't enough. You might need to check multiple things at once. Logical operators allow you to combine boolean expressions into a single, more complex boolean result.

AND (&&)

The && operator requires both sides of the expression to be true for the result to be true. If either side is false, the result is false.

  • true && truetrue
  • true && falsefalse
  • false && falsefalse

Example:

bool hasPassword = true;
bool hasUsername = true;

// Both must be true to log in
if (hasUsername && hasPassword)
{
    Console.WriteLine("Logging in...");
}

OR (||)

The || operator requires at least one side of the expression to be true. The result is only false if both sides are false.

  • true || truetrue
  • true || falsetrue
  • false || falsefalse

Example:

bool isWeekend = true;
bool isHoliday = false;

// If it is a weekend OR a holiday, we sleep in
if (isWeekend || isHoliday)
{
    Console.WriteLine("Sleeping until noon.");
}

NOT (!)

The ! operator inverts a boolean value. It turns true into false and false into true.

Example:

bool isBanned = false;

// Checking if the user is NOT banned
if (!isBanned) 
{
    Console.WriteLine("Post allowed.");
}

Visualizing Control Flow

The logic of if/else/else if creates a decision tree. Here is a visualization of a login system using Graphviz.

A decision tree diagram visualizes the control flow of a login system, branching from the initial entry point into distinct paths for successful authentication, failed attempts, and locked accounts.
Hold "Ctrl" to enable pan & zoom

A decision tree diagram visualizes the control flow of a login system, branching from the initial entry point into distinct paths for successful authentication, failed attempts, and locked accounts.

Practical Patterns and Pitfalls

1. String Comparison Sensitivity

As seen in the ticket example, comparing strings with == is case-sensitive. "yes" is not the same as "Yes". In AI applications, this is critical when processing natural language input. To handle this, you often convert inputs to a standard case before comparing.

string input = "Yes"; // User typed capital Y
// This would fail:
if (input == "yes") { ... } 

// This succeeds:
if (input.ToLower() == "yes") { ... } 
(Note: We use ToLower() here, which is a method on strings introduced in Chapter 2/3 concepts).

2. Assignment vs. Comparison

A common beginner mistake is using = instead of ==.

int x = 5;

// WRONG: This assigns 5 to x, and the result of the assignment is 5.
// In C#, non-zero numbers are treated as 'true' in some contexts, leading to bugs.
if (x = 5) { ... } 

// CORRECT: This checks if x equals 5.
if (x == 5) { ... }

3. Floating Point Precision

When comparing double types (Chapter 2), direct equality checks can be unreliable due to how computers store decimal numbers.

double a = 1.0 / 3.0; // 0.333333...
double b = 0.333333;
if (a == b) { ... } // This might be false due to tiny precision differences.
For AI calculations involving probabilities (which are often decimals), it is safer to check if the difference is smaller than a tiny threshold (epsilon), though this requires math concepts beyond the current strict scope. For now, be aware that == on double can be tricky.

AI Application Context

In AI development, if/else logic is the "guardrail" system. While the AI model (like a Large Language Model) might generate creative text, the surrounding C# code uses strict boolean logic to ensure safety and structure.

Scenario: A Chatbot Response Filter Imagine you are building a chatbot. You receive a response from an AI model, but you must check if it contains inappropriate content before showing it to the user.

  1. Input: The AI generates the string: "I don't know the answer, but I can try to help."
  2. Variable: string aiResponse = ...;
  3. Logic:
    • Check if the response is empty.
    • Check if the response contains banned words (using string comparison).
    • Check if the response length is too long.
using System;

class ChatbotFilter
{
    static void Main()
    {
        // Simulated AI response
        string aiResponse = "I cannot help with that request.";
        bool isSafe = true; // Assume safe until proven otherwise

        // Check 1: Is the response empty?
        if (aiResponse == "")
        {
            isSafe = false;
        }

        // Check 2: Does it contain a banned word? (Simple check)
        // Note: This is a basic example. Real AI filters are much more complex.
        if (aiResponse.Contains("banned_word")) 
        {
            // We are simulating a method call here. 
            // In a real app, this would be a string method.
            isSafe = false;
        }

        // Decision: Show response or error
        if (isSafe)
        {
            Console.WriteLine($"Bot: {aiResponse}");
        }
        else
        {
            Console.WriteLine("Bot: I am sorry, I cannot generate a response to that.");
        }
    }
}

Theoretical Foundations

  1. Booleans are the atomic unit of decision-making (true/false).
  2. Comparison Operators (==, !=, >, <, >=, <=) are the tools used to generate booleans by comparing variables and literals.
  3. Logical Operators (&&, ||, !) allow you to combine multiple comparisons into a single complex decision.
  4. Control Structures (if, else if, else) are the mechanisms that execute different blocks of code based on the boolean results.

By mastering these concepts, you move from writing linear scripts (which do the same thing every time) to writing dynamic programs that react to data, user input, and the complex world of AI decision-making.

Basic Code Example

Here is a simple code example demonstrating the use of if and else statements to make a decision based on user input.

using System;

class Program
{
    static void Main()
    {
        // 1. Prompt the user to enter their age
        Console.WriteLine("Please enter your age:");

        // 2. Read the user's input from the console
        string input = Console.ReadLine();

        // 3. Convert the string input to an integer for comparison
        int age = int.Parse(input);

        // 4. Check if the age is 18 or older
        if (age >= 18)
        {
            // 5. If true, confirm they are an adult
            Console.WriteLine("You are an adult.");
        }
        // 6. If the condition above was false, execute this block
        else
        {
            // 7. Inform the user they are a minor
            Console.WriteLine("You are a minor.");
        }
    }
}

Explanation

  1. User Prompt: We use Console.WriteLine to display a message asking the user to input their age. This sets the context for the user.
  2. Input Capture: Console.ReadLine() captures the keystrokes the user types until they press Enter. This input is stored as a string in the variable input.
  3. Type Conversion: Since we need to compare numbers (age), we convert the string to an integer using int.Parse(). This allows us to perform mathematical comparisons like >=.
  4. The if Statement: This is the decision point. if (age >= 18) asks the question: "Is the value of age greater than or equal to 18?"
  5. The True Path: If the condition in step 4 is true, the code inside the curly braces { } following the if statement runs. In this case, it prints "You are an adult."
  6. The else Statement: This keyword catches the scenario where the if condition was false. It does not require a condition because it is the default "catch-all" for when the if check fails.
  7. The False Path: If age is less than 18, the code inside the else braces runs, printing "You are a minor."

Visualizing the Flow

The logic follows a binary path: the program evaluates a condition and diverges into one of two execution paths.

Diagram: G
Hold "Ctrl" to enable pan & zoom

Common Pitfalls

Forgetting Braces {} A common mistake for beginners is writing an if statement without curly braces for single-line actions, like this:

if (age >= 18)
    Console.WriteLine("You are an adult."); // Only this line is conditional
    Console.WriteLine("Welcome!");          // This line ALWAYS runs
In C#, only the statement immediately following the if (or else) is controlled by the condition. The second Console.WriteLine will execute regardless of the user's age because it is not inside the braces. Always use curly braces {} to group your code blocks to avoid logic errors and to make your code easier to read and modify later.

The chapter continues with advanced code, exercises and solutions with analysis, you can find them on the ebook on Leanpub.com or Amazon



Code License: All code examples are released under the MIT License. Github repo.

Content Copyright: Copyright © 2026 Edgar Milvus | Privacy & Cookie Policy. All rights reserved.

All textual explanations, original diagrams, and illustrations are the intellectual property of the author. To support the maintenance of this site via AdSense, please read this content exclusively online. Copying, redistribution, or reproduction is strictly prohibited.