An iterator is a method in C# which is used in an array or in collections like the list, etc. to retrieve elements one by one. Or in other words, we can say that an iterator is used to perform an iteration over the collections. This feature is introduced in C# 2.0. It uses the yield return statement to return the element from the collection at a time and it always remembers the current location of the iterator, so when the next iteration takes place it will return the next element of the given collection. If you want to stop the iteration you will use the yield break statement.
The return type of this method is IEnumerable, IEnumerable, IEnumerator, or IEnumerator. Which means by using iterator compiler will automatically create IEnumerable or IEnumerator interface for you there is no need to implement IEnumerable or IEnumerator interface in your class for using a foreach loop. When the compiler identifies an iterator in your class it will automatically create the current, MoveNext and dispose of the method of IEnumerable or IEnumerator interface.
- Iterator can be used as a method, or as a property.
- Iterator method is also known as get accessor.
- You can use iterator as a method or get accessor.
- You cannot use iterator in an events instance constructor, static constructor, or static finalizer.
- An iterator method does not contain ref, or out parameters.
- Here, yield is not reserved word, but when you use use yield with return or break statement, then yield have special meaning.
- You are allowed to use multiple yield statements.
- It is generally used with generic or non-generic collections.
- When you are working with iterator it is necessary to add
System.Collections.Genericnamespace in your program.
Cat Goat Dog Cow
Geeks geeks123 1234geeks
- Automation Using Selenium in C# With Example
- How to Execute C# Program on cmd (command-line)?
- How to Install and Setup Visual Studio for C#?
- What is .NET 3-Tier Architecture?
- Cross Join in LINQ
- Comparing two ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> in C#
- Compare two ValueTuple<T1, T2, T3, T4, T5, T6, T7> in C#
- Comparing two ValueTuple<T1, T2, T3, T4, T5, T6> in C#
- Comparing two ValueTuple<T1, T2, T3, T4, T5> in C#
- Comparing two ValueTuple<T1, T2, T3, T4> in C#
- Comparing two ValueTuple<T1, T2, T3> in C#
- Comparing two ValueTuple<T1, T2> in C#
- Comparing two ValueTuple<T1> in C#
- Checking if two ValueTuple<T1,T2,T3,T4,T5,T6,T7,TRest> are equal or not in C#
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.