capypad
0 day streak
csharp / intermediate
Snippet

Deferred Execution with 'yield return'

The 'yield return' statement indicates that the method is an iterator. It provides a value to the enumerator without generating the entire collection in memory at once, enabling efficient processing of large data sets.

snippet.csharp
csharp
1
2
3
4
5
6
7
public IEnumerable<int> GetEvenNumbers(int max)
{
for (int i = 0; i <= max; i++)
{
if (i % 2 == 0) yield return i;
}
}
Breakdown
1
IEnumerable<int>
The return type must be an interface that supports iteration, such as IEnumerable.
2
yield return i
Returns the current value and pauses the method execution until the next element is requested by the caller.