07
Lesson 7 of 35 ยท Control Flow

Control Flow: if / else

Programs need to make decisions. The if/else statement is the most fundamental control-flow construct in C#. This lesson covers simple conditions, else-if chains, nested ifs, and the modern pattern-matching enhancements in C# 14.

The if Statement

The if statement evaluates a boolean expression. If it is true, the body executes. The body can be a single statement or a block surrounded by curly braces. Always use braces to avoid bugs when adding extra lines later.

Simple if If.cs
int temperature = 35;

if (temperature > 30)
{
    Console.WriteLine("It's hot outside!");
}

if / else and else if

Add an else block to handle the false case. Chain multiple conditions with else if. Only the first matching block executes; the rest are skipped.

if-else chain IfElse.cs
int score = 72;

if (score >= 90)
    Console.WriteLine("Grade: A");
else if (score >= 80)
    Console.WriteLine("Grade: B");
else if (score >= 70)
    Console.WriteLine("Grade: C");
else if (score >= 60)
    Console.WriteLine("Grade: D");
else
    Console.WriteLine("Grade: F");

Nested if Statements

You can place an if inside another if. Keep nesting shallow (maximum 2โ€“3 levels) to maintain readability. Consider early-return patterns or guard clauses to avoid deep nesting.

Guard clause pattern Guard.cs
static void ProcessOrder(Order? order)
{
    if (order == null)       return; // guard
    if (!order.IsValid)      return; // guard
    if (order.Total <= 0)    return; // guard

    // Happy path โ€” no deep nesting
    Console.WriteLine($"Processing order #{order.Id}");
}

Pattern Matching in if

C# supports type patterns (is TypeName variable), relational patterns, and logical patterns (and, or, not) directly inside if conditions.

Pattern matching Patterns.cs
object obj = 42;

// Type pattern
if (obj is int number)
    Console.WriteLine($"Integer: {number}");

// Relational pattern
int age = 25;
if (age is >= 18 and <= 65)
    Console.WriteLine("Working age");

// Negation pattern
string? name = null;
if (name is not null)
    Console.WriteLine(name);