yield break and Early Termination
Stop iteration conditionally.
yield break and Early Termination is a free C# Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Stopping an Iterator Early
Sometimes you want an iterator to stop producing values before reaching the natural end. The yield break statement ends the sequence immediately, like a return for iterators.
Basic yield break
yield break terminates the iterator. No further values are produced and the foreach loop consuming it ends.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> UpToFive()
{
for (int i = 1; i <= 100; i++)
{
if (i > 5) yield break;
yield return i;
}
}
public static void Main()
{
foreach (var n in UpToFive())
Console.WriteLine(n);
}
}Take While a Condition Holds
A common pattern is to yield items only while a condition is true, then stop. yield break makes this clean.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> WhileSmall(IEnumerable<int> nums)
{
foreach (var n in nums)
{
if (n >= 10) yield break;
yield return n;
}
}
public static void Main()
{
foreach (var n in WhileSmall(new[] { 2, 4, 8, 12, 3 }))
Console.WriteLine(n);
}
}Guard Clauses With yield break
You can use yield break at the top of an iterator as a guard. If the input is empty or invalid, return no items at all.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static IEnumerable<string> Lines(string text)
{
if (string.IsNullOrEmpty(text)) yield break;
foreach (var line in text.Split('\n'))
yield return line;
}
public static void Main()
{
foreach (var l in Lines("a\nb\nc"))
Console.WriteLine(l);
Console.WriteLine("empty count: " + Lines("").Count());
}
}Limiting Output Count
Use a counter plus yield break to cap how many items an iterator produces, even from a long source.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> Take(IEnumerable<int> source, int max)
{
int count = 0;
foreach (var item in source)
{
if (count++ >= max) yield break;
yield return item;
}
}
public static void Main()
{
foreach (var n in Take(new[] { 1, 2, 3, 4, 5 }, 3))
Console.WriteLine(n);
}
}Caller break vs yield break
There are two ways a sequence can end. The caller can stop pulling with break, or the iterator can stop producing with yield break. Both end the loop, but for different reasons.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> Counting()
{
int i = 1;
while (true) yield return i++;
}
public static void Main()
{
// Caller decides to stop with break
foreach (var n in Counting())
{
if (n > 3) break;
Console.WriteLine(n);
}
}
}yield break Ends Only the Current Iterator
yield break exits the iterator method it appears in, not any outer loop in the caller. Control returns to whoever was enumerating.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> Bounded(IEnumerable<int> nums, int limit)
{
foreach (var n in nums)
{
if (n > limit) yield break; // ends Bounded only
yield return n;
}
}
public static void Main()
{
var result = Bounded(new[] { 1, 2, 9, 3 }, 5);
Console.WriteLine("iterator created, still running");
foreach (var n in result) Console.WriteLine(n);
}
}No yield return After yield break
Once yield break executes, the iterator is finished. Any code physically after it in the same path is unreachable for value production.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> Demo(bool stopEarly)
{
yield return 1;
if (stopEarly) yield break;
yield return 2;
yield return 3;
}
public static void Main()
{
Console.WriteLine("stopEarly = true:");
foreach (var n in Demo(true)) Console.WriteLine(n);
Console.WriteLine("stopEarly = false:");
foreach (var n in Demo(false)) Console.WriteLine(n);
}
}Combining Filter and Early Stop
You can filter and terminate in the same iterator: skip some values, yield others, and bail out entirely when a sentinel appears.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> UntilZero(IEnumerable<int> nums)
{
foreach (var n in nums)
{
if (n == 0) yield break; // stop at sentinel
if (n < 0) continue; // skip negatives
yield return n;
}
}
public static void Main()
{
foreach (var n in UntilZero(new[] { 3, -1, 5, 0, 9 }))
Console.WriteLine(n);
}
}yield break and finally Blocks
If your iterator has a try/finally, the finally still runs when yield break ends the sequence. This guarantees cleanup like closing resources.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> WithCleanup()
{
try
{
yield return 1;
yield break;
}
finally
{
Console.WriteLine("cleanup ran");
}
}
public static void Main()
{
foreach (var n in WithCleanup())
Console.WriteLine(n);
}
}Try It Yourself
Combine filtering and early termination: yield positive numbers but stop entirely once their running sum exceeds a budget.
using System;
using System.Collections.Generic;
public class Program
{
static IEnumerable<int> WithinBudget(IEnumerable<int> nums, int budget)
{
int spent = 0;
foreach (var n in nums)
{
if (n <= 0) continue;
if (spent + n > budget) yield break;
spent += n;
yield return n;
}
}
public static void Main()
{
foreach (var n in WithinBudget(new[] { 3, -2, 4, 5, 1 }, 10))
Console.WriteLine(n);
}
}Quick Check
Recall the role of yield break.
Recap
yield break ends an iterator early.
- It works like a value-less
returnfor iterators. - Use it for take-while logic, guards, and count limits.
- It ends only the iterator, not the caller loop.
finallyblocks still run, ensuring cleanup.
Frequently asked questions
Is the “yield break and Early Termination” lesson free?
Yes — the full text of “yield break and Early Termination” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “yield break and Early Termination”?
Stop iteration conditionally. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “yield break and Early Termination” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Iterator Methods with yield return
- yield break and Early Termination
- Lazy Evaluation Semantics
- Custom Enumerables