
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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); }
- Related Articles
- Iterator Functions in Python
- Iterator Functions in Java
- Using iterator functions in Javascript
- Iterator Invalidation in C++
- RLE Iterator in C++
- Zigzag Iterator in C++
- Iterator Invalidation in C++ program
- Iterator for Combination in C++
- Binary Search Tree Iterator in C++
- Difference between Iterator and Spilt Iterator in Java.
- Iterator in Java
- Thread functions in C/C++
- Functions in C/C++(3.5)
- Iterator function in Python
- Time Functions in C#

Advertisements