Member-only story

Iterators in C#

Shahzad Aslam
2 min readJul 17, 2024

--

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.

Iterators in C#

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>…

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

No responses yet