Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the use of yield return in C#?
The yield return keyword in C# enables lazy evaluation and custom iteration over collections. When you use yield return, the method becomes an iterator that returns values one at a time, pausing execution between each return and resuming where it left off when the next value is requested.
Syntax
Following is the syntax for using yield return −
public static IEnumerable<T> MethodName() {
// some logic
yield return value;
// more logic
yield return anotherValue;
}
You can also use yield break to terminate the iteration early −
yield break; // stops the iteration
How It Works
When a method contains yield return, the compiler generates a state machine that maintains the method's local variables and execution position between calls. This allows the method to pause and resume execution seamlessly.
Using yield return for Running Totals
Example
using System;
using System.Collections.Generic;
class Program {
static List<int> numbersList = new List<int> {
1, 2, 3, 4, 5
};
public static void Main() {
foreach(int i in RunningTotal()) {
Console.WriteLine(i);
}
}
public static IEnumerable<int> RunningTotal() {
int runningTotal = 0;
foreach(int i in numbersList) {
runningTotal += i;
yield return runningTotal;
}
}
}
The output of the above code is −
1 3 6 10 15
Using yield return for Fibonacci Sequence
Example
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
public static void Main() {
foreach(int fib in GenerateFibonacci().Take(10)) {
Console.Write(fib + " ");
}
}
public static IEnumerable<int> GenerateFibonacci() {
int a = 0, b = 1;
yield return a;
yield return b;
while(true) {
int next = a + b;
yield return next;
a = b;
b = next;
}
}
}
The output of the above code is −
0 1 1 2 3 5 8 13 21 34
Using yield break
Example
using System;
using System.Collections.Generic;
class Program {
public static void Main() {
foreach(int number in GetNumbersUntilNegative()) {
Console.WriteLine(number);
}
}
public static IEnumerable<int> GetNumbersUntilNegative() {
int[] numbers = {1, 5, 3, -2, 7, 9};
foreach(int num in numbers) {
if(num < 0) {
yield break; // stops iteration
}
yield return num;
}
}
}
The output of the above code is −
1 5 3
Key Benefits
-
Memory Efficiency: Values are generated on-demand rather than storing entire collections in memory.
-
Lazy Evaluation: Computation is deferred until the value is actually needed.
-
State Preservation: Local variables maintain their values between iterations.
-
Infinite Sequences: Can generate potentially infinite sequences without running out of memory.
Conclusion
The yield return keyword creates iterator methods that generate values on-demand, providing memory-efficient lazy evaluation. It's particularly useful for processing large datasets, generating sequences, and creating custom enumerable collections without loading all data into memory at once.
