Javatpoint Logo
Javatpoint Logo

C# Iterators

C# iterator is a method. It is used to iterate the elements of a collection, array or list. An iterator uses yield return statement to return each element at a time.

The iterator remembers the current location and in next iteration, it returns the next element.

The return type of an iterator can be IEnumerable<T> or IEnumerator<T>.

To stop iteration, we can use yield break statement.

C# Iterator Example 1

In this example, we are iterating array elements.

Output:

5
8
6
9
1

Iterator can also be used to iterate collection elements. In the following example, we are iterating list elements.

C# Iterator Example 2

Output:

Rohan
Peter
Irfan
Sohan

Next TopicC# Nullable




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA