Member-only story
Iterators in C#
In C#, iterators provide a convenient way to iterate over collections or sequences of data. They allow you to define custom iteration behavior for your classes, similar to how you use foreach with built-in collections like arrays or lists.
1. Iterator Methods (yield Keyword)
Iterator methods in C# are defined using the yield keyword. This keyword is used to return each element of the collection one at a time, which allows the caller to iterate over the collection without loading the entire sequence into memory at once.
Syntax
public IEnumerable MyIteratorMethod()
{
// yield return statements
}
1. Return Type:
Iterator methods typically return IEnumerable<T>, IEnumerable<T>, or a custom type implementing IEnumerable<T>;.
2. yield return:
This statement returns each element of the sequence one-by-one. The method execution is paused, and the current state is preserved, allowing the caller to retrieve the yielded value.
3. yield break:
This statement signals the end of the iteration. It terminates the iteration and returns control to the caller.
Example
public IEnumerable<int>…