0 day streak
csharp / expert
Snippet

Stateful Iterators for Deferred Complex Logic

The 'yield' keyword transforms a method into a state machine. This allows for complex control flow and sequences to be generated lazily, preventing unnecessary memory allocations for large datasets.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
public static IEnumerable<long> FibonacciSequence(int limit) {
long prev = 0, current = 1;
for (int i = 0; i < limit; i++) {
yield return prev;
long next = prev + current;
prev = current;
current = next;
}
}
// Usage: var data = FibonacciSequence(10).Where(n => n % 2 == 0);
Breakdown
1
yield return prev;
Suspends execution and returns a value to the caller, preserving the local state for the next iteration.
2
IEnumerable<long>
Defines the return type as a lazy sequence that only executes when iterated over (deferred execution).