 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterator Functions in C#
An iterator method performs a custom iteration over a collection. It uses the yield return statement and returns each element one at a time. The iterator remembers the current location and in the next iteration the next element is returned.
The following is an example −
Example
using System; using System.Collections.Generic; using System.Linq; namespace Demo {    class Program {       public static IEnumerable display() {          int[] arr = new int[] {99,45,76};          foreach (var val in arr) {             yield return val.ToString();          }       }       public static void Main(string[] args) {          IEnumerable ele = display();          foreach (var element in ele) {             Console.WriteLine(element);          }         }    } }  Output
99 45 76
Above, we have an iterator method display() that use the yield statement to return one element at a time −
public static IEnumerable display() {    int[] arr = new int[] {99,45,76};    foreach (var val in arr) {       yield return val.ToString();    } } The result is stored and each element is iterated and printed −
IEnumerable ele = display(); foreach (var element in ele) {    Console.WriteLine(element); }Advertisements
 