
- 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
What is the use of yield return in C#?
Yield keyword helps to do custom stateful iteration over a collection. Meaning when we use yield keyword the control moves back and forth from the caller function to source and vice versa.
Example
using System; using System.Collections.Generic; namespace DemoApplication { 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); } Console.ReadLine(); } public static IEnumerable<int> RunningTotal() { int runningTotal = 0; foreach(int i in numbersList) { runningTotal += i; yield return (runningTotal); } } } }
Output
The output of the above program is
1 3 6 10 15
In the above example, in the for each of the main method we are looping through the numbers list of the running total. So whenever the yield return is called the control goes back to main method for each loop and prints the values. Once after printing the value the control again goes to for each of the running total. One thing that needs to noted here is that the previous value is also preserved. So simply, yield keyword effectively creates a lazy enumeration over collection items that can be much more efficient.
- Related Articles
- When to use yield instead of return in Python?
- Difference between Yield and Return in Python?
- What is the usage of yield keyword in JavaScript?
- What is the yield keyword in JavaScript?
- What is the use of return statement inside a function in JavaScript?
- How exactly do Python functions return/yield objects?
- What are Yield to Maturity, Yield to Call, and Current Yield?
- Yield Curve and Inverted Yield Curve
- Importance of yield() method in Java?
- The yield* expression/keyword in JavaScript.
- What are the important conditions for ensuring a better yield of crops?
- What is the return type of a Constructor in Java?
- What is the use of "is" keyword in C#?
- How to use the return statement in C#?
- What is the use of sinon.js?

Advertisements