C# Programming Tutorial 0/45 lessons ~6 min read Lesson 10

    Break & Continue

    break exits the nearest loop or switch; continue skips to the next iteration.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    break exits the nearest loop or switch; continue skips to the next iteration. They simplify search loops — break when found, continue when skipping invalid rows — but overuse creates spaghetti flow interviewers ask you to refactor.

    Labeled break is not available in C# (unlike Java). Nested loops require flags or extracted methods instead of breaking outer loops directly. In modern code, LINQ FirstOrDefault or TryFind patterns often replace break-based search.

    Understand when control statements clarify intent vs when they obscure it — senior reviews flag continue abuse in 200-line methods.

    The story

    A fraud team scans a stream of credit-card payments to find the first suspicious charge. Government tax payments and utility bills are on a trusted-merchant list and should be skipped instantly — there is no reason to flag them.

    continue skips trusted merchants; returning early from the loop avoids scanning the entire day's transactions once the first problem payment is found.

    Understanding the topic

    Key concepts

    • break exits innermost switch, for, foreach, while, do.
    • continue jumps to next iteration of innermost loop.
    • Cannot break/continue outside loop or switch — compile error.
    • goto exists but discouraged except in generated code.
    • return also exits method — often cleaner than break in nested logic.
    • LINQ methods like TakeWhile replace manual break patterns.

    Step-by-step explanation

    1. break in switch prevents fall-through to next case.
    2. continue in for loop skips increment until next cycle — actually jumps to increment step.
    3. Nested search: set found flag and break inner, check flag outer.
    4. Extract method returning bool for cleaner early exit.
    5. Switch in loop: break only exits switch, not loop — use flag.
    6. Performance: break early avoids unnecessary iterations.

    Practical code example

    Find first fraudulent transaction — break on match; continue to skip whitelisted merchants:

    csharp
    namespace TechLearningPro.BreakContinue;
    public record Payment(string MerchantId, decimal Amount, bool IsFlagged);
    public static class FraudScanner
    {
    private static readonly HashSet<string> Trusted = ["GOV-TAX", "UTIL-ELECTRIC"];
    public static Payment? FindFirstSuspicious(IEnumerable<Payment> payments)
    {
    foreach (var p in payments)
    {
    if (Trusted.Contains(p.MerchantId))
    continue;
    if (p.IsFlagged || p.Amount > 10_000m)
    return p; // clearer than break + temp variable
    }
    return null;
    }
    }

    Line-by-line code explanation

    • public record Payment(string MerchantId, decimal Amount, bool IsFlagged) captures the fields the scanner inspects.
    • HashSet<string> Trusted stores trusted merchant IDs for O(1) lookup performance.
    • ["GOV-TAX", "UTIL-ELECTRIC"] is a collection expression initializing the trusted set.
    • foreach (var p in payments) walks each payment in arrival order.
    • if (Trusted.Contains(p.MerchantId)) continue skips trusted merchants immediately.
    • continue jumps to the next iteration without evaluating the suspicion check.
    • if (p.IsFlagged || p.Amount > 10_000m) detects manually flagged or very large charges.
    • return p exits the method with the first suspicious payment found.
    • return null after the loop means no suspicious payment was detected.

    Key takeaway: return inside loop often reads better than break + nullable result. continue skips trusted merchants efficiently.

    Real-world use

    Where you'll use this in production

    • Parsing files — skip comment lines with continue.
    • Game loops — break on quit command.
    • Retry loops — break on success, continue on transient error.
    • Switch dispatch — break after each case handler.

    Best practices

    • Prefer return or LINQ over break when searching.
    • Limit continue to top-of-loop skip conditions.
    • Document why loop exits early.
    • Use labeled comments if break target unclear.
    • Refactor nested break logic into separate methods.

    Common mistakes

    • break only exits switch inside loop — infinite outer loop.
    • continue skipping increment logic incorrectly in while.
    • break in foreach then code after loop assumes not found — logic bugs.
    • Excessive continue making loop body unreadable.

    Advanced interview questions

    Q1BeginnerWhat does break do in a loop?
    Exits the innermost enclosing loop immediately.
    Q2Beginnercontinue vs break?
    continue next iteration; break exits loop entirely.
    Q3IntermediateBreak out of nested loops in C#?
    No labeled break — use goto (rare), return, or extract method with bool.
    Q4IntermediateReplace break search with LINQ?
    FirstOrDefault(predicate) or TryGet pattern with IEnumerable.
    Q5AdvancedReview loop with four continue statements — refactor approach?
    Extract filter predicates, use Where before loop, or split into pipeline stages with early return methods.

    Summary

    break exits loop/switch; continue skips to next iteration. C# lacks labeled break — use methods or flags for nested exit. return and LINQ often express intent clearer than break. Use continue sparingly for top-of-loop guards. Next: advanced pattern matching beyond switch.

    Ready to mark this lesson complete?Track your journey across the entire course.