Learn C# · 3/15

Control Flow: Directing Your Program

7 min read

Hello, camper! 👋 Welcome to Module 3.

Up until now, your code has been like a bowling ball rolling down a lane with the bumpers up—straight, linear, and hitting the pins at the end no matter what. It executes line 1, then line 2, then line 3.

But real software is more like a choose-your-own-adventure book. Sometimes you need to jump pages, skip paragraphs, or read the same sentence ten times until you memorize it.

Control Flow is the art of telling your computer which lines of code to execute and when. Without it, you can't build logic. You just have a script.


1. Conditional Logic: If, Else, and Else If

The Problem

Imagine you are building a banking app. You want to let a user withdraw money.
If you just write balance = balance - amount;, the program will let them withdraw $1,000,000 even if they have $5. That is bad business. We need a way to execute code only when specific criteria are met.

The Concept

The if statement evaluates a Boolean expression (something that is either true or false).

  • If true: Enter the block and run the code.
  • If false: Skip the block entirely.

We can extend this with else (do this if the first thing failed) and else if (check a new condition if the first failed).

In Practice

Here is how we handle that bank withdrawal safely:

csharp
int balance = 100;
int withdrawalRequest = 150;

// The "if" statement checks the condition inside parentheses
if (withdrawalRequest <= balance)
{
    // This runs ONLY if the condition is true
    balance -= withdrawalRequest;
    Console.WriteLine("Here is your money! 💸");
}
else if (withdrawalRequest > 1000)
{
    // This runs if the first 'if' was false AND this condition is true
    Console.WriteLine("We don't keep that much cash in the ATM!");
}
else
{
    // This runs if ALL previous conditions were false
    Console.WriteLine("Insufficient funds. You are broke. 📉");
}

💡 Industry Standard: Guard Clauses

New developers often create "Arrow Code"—logic nested so deep it looks like an arrow >. It is hard to read.

Bad (Nested):

csharp
if (user != null) {
    if (user.IsActive) {
        if (user.HasAccess) {
             // Do work
        }
    }
}

Good (Guard Clauses):
Check for failure first and return early. This keeps the "happy path" (the main logic) unindented.

csharp
if (user == null) return;
if (!user.IsActive) return;
if (!user.HasAccess) return;

// Do work - look how clean this is! ✨

Fun Fact: The first bug in history was an actual moth trapped in a relay of the Harvard Mark II computer in 1947. Conditional logic is where "logic bugs" usually hide today—no insects required.


2. Switch Statements and Expressions

The Problem

What if you need to check a single variable against 10 different possible values?
Using if (x == 1) ... else if (x == 2) ... else if (x == 3) is messy, slow to read, and ugly.

The Concept

The switch statement selects a single switch section to execute from a list of candidates based on a pattern match with the match expression.

The Classic Switch (Statement)

This is the legacy way, but you will see it in older codebases often.

csharp
string role = "Admin";

switch (role)
{
    case "Admin":
        Console.WriteLine("Full Access 🔓");
        break; // You MUST include break (or return), or C# gets angry.
    case "User":
        Console.WriteLine("Limited Access 🛡️");
        break;
    case "Guest":
        Console.WriteLine("Read Only 👁️");
        break;
    default:
        Console.WriteLine("Unknown Role 🚫");
        break;
}

The Modern Switch (Expression) - C# 8.0+

Since C# 8, we have Switch Expressions. This is what you should use in modern development if you are assigning a value based on a condition. It is concise, uses "lambda arrow" syntax, and doesn't need break.

csharp
string role = "Admin";

// Notice the semicolon is at the end of the curly brace, not inside cases
string message = role switch
{
    "Admin" => "Full Access 🔓",
    "User"  => "Limited Access 🛡️",
    "Guest" => "Read Only 👁️",
    _       => "Unknown Role 🚫" // The underscore '_' represents "default"
};

Console.WriteLine(message);

💡 Industry Standard

Use Switch Expressions whenever you are transforming one value into another (e.g., converting a Status Enum to a Color String). Use Switch Statements only when you need to execute complex logic blocks with multiple lines of code per case.


3. Looping: For, While, and Do-While

The Problem

You need to print "Hello World" 500 times.
Copy-pasting Console.WriteLine 500 times is a violation of the DRY principle (Don't Repeat Yourself) and a fast way to get Carpal Tunnel syndrome.

The Concept

Loops allow you to repeat a block of code until a specific condition becomes false.

A. The While Loop

"Check the ID card before letting them into the club."
The condition is evaluated before the loop runs. If it's false initially, the loop never runs.

csharp
int power = 0;

// Runs while power is less than 5
while (power < 5)
{
    Console.WriteLine($"Charging... {power}%");
    power++; // CRITICAL: You must change the variable, or you get an Infinite Loop ♾️
}

B. The Do-While Loop

"Let them into the club, then check the ID card."
The code block runs at least once, regardless of the condition. This is great for "Press any key to quit" scenarios.

csharp
int input = 0;
do 
{
    Console.WriteLine("I will run at least once!");
    input++;
} while (input < 0); // Condition is false, but it already ran once.

C. The For Loop

This is the precision tool. Use this when you know exactly how many times you need to iterate.

Structure: for (initializer; condition; iterator)

csharp
// i starts at 0.
// Keep running as long as i < 5.
// After every loop, add 1 to i (i++).
for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"Lap number {i}");
}

Imagination Time: Think of a for loop like a mesmerizing mechanical clock. The gears (iterator) turn exactly one notch every time the pendulum swings, until the alarm (condition) triggers. 🕰️


4. Iterating Collections: The Foreach Loop

The Problem

for loops are powerful, but they are dangerous with arrays or lists.
If you have a list of 5 items and you try to access item #6 (index 5, because we start counting at 0), your program crashes with an IndexOutOfRangeException.
Also, manually managing the index i is tedious.

The Concept

The foreach loop is designed specifically for collections (Arrays, Lists). It says: "For every item inside this bag, pick it up, call it 'item', do something with it, then put it down and grab the next one."

It creates a read-only iteration variable.

csharp
string[] inventory = { "Sword", "Shield", "Potion", "Map" };

// "item" represents the current element
foreach (string item in inventory)
{
    Console.WriteLine($"You have equipped: {item}");
}

Under the Hood

foreach only works on objects that implement the IEnumerable interface. It asks the collection for an Enumerator, which is a tiny cursor that knows how to move to the .Next() item.

💡 Industry Standard: Modification Warning

You cannot modify the collection inside a foreach loop.

This will crash:

csharp
List<int> numbers = new List<int> { 1, 2, 3 };
foreach (int num in numbers)
{
    if(num == 2) 
    {
        numbers.Remove(num); // 🚨 ERROR: Collection was modified; enumeration operation may not execute.
    }
}

Solution: If you need to modify a list while looping, use a for loop iterating backwards, or creating a separate list of items to remove.


Summary of Control Flow Best Practices

  1. Use Guard Clauses: Return early to avoid deep if/else nesting.
  2. Switch Expressions: Use the modern => syntax for cleaner code when assigning values.
  3. Foreach is King: Use foreach for lists and arrays unless you absolutely need the index number.
  4. Avoid Infinite Loops: Always ensure your while loop has an exit condition that will eventually be met.

Now you are the traffic controller of your code. You decide where the data goes! 🚦


🔗 Helpful References (Docs)

Challenge

You are tasked with implementing the logic for an e-commerce order processor.

Complete the CalculateOrderTotal method within the provided OrderProcessor class. This method takes a list of Product objects and a discount code string.

Your implementation must follow these business rules precisely:

  1. Input Validation: If the input products list is null or contains no items, the method must return 0m immediately. This is a guard clause.
  2. Product Iteration: You must iterate over every product in the list.
  3. Price Calculation: For each product, calculate its price based on its Category. You must use a switch expression for this logic:
    • Category.Electronics: BasePrice * 1.15m
    • Category.Apparel: BasePrice * 1.20m
    • Category.Groceries: BasePrice * 1.05m
    • Any other category: BasePrice * 1.25m (default tax)
  4. Total Accumulation: Sum the calculated prices of all products to get a subtotal.
  5. Discount Application: After calculating the subtotal, apply a discount based on the discountCode string:
    • If the code is "PROMO20", apply a 20% discount.
    • If the code is "SAVE10", apply a 10% discount.
    • For any other code (or no code), apply no discount.
  6. Return Value: Return the final calculated total as a decimal.

Expected result

Your completed CalculateOrderTotal method should correctly implement all the specified business logic.

A correct solution will feature:

  • An initial guard clause checking if products is null or empty, returning 0m if true.
  • A foreach loop to iterate through the products list.
  • A C# 8.0+ switch expression (using => syntax) inside the loop to calculate the price for each product based on its category.
  • An if-else if-else structure after the loop to correctly apply the final discount to the accumulated total before returning it.

For example, if called with a list containing one Electronics product with a BasePrice of 100m and the discount code "PROMO20", the final result should be (100m * 1.15m) * 0.80m, which is 92.0m.

csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.