C# yield keyword (With Examples) (2024)

The yield keyword performs custom iteration over a collection like list, array, etc.

Two Forms of yield Keyword

The yield keyword is used in two forms:

  • yield return - returns an expression at each iteration
  • yield break - terminates the iteration

yield return in an Iterator

The yield keyword is used in an iterator as:

yield return <expression>; 

We use yield return inside an iterator as:

using System;using System.Collections.Generic;class Program{ // define an iterator method static IEnumerable<int> getNumber() { // create a list of integers List<int> myList = new List<int> { -1, -4, 3, 5 }; foreach (var num in myList) { // returns positive number from myList 

if (num >= 0) { yield return num; // location of the code is preserved // so on the next iteration getNumber() is executed from here Console.WriteLine("...."); }

} } static void Main() { // display return values of getNumber() foreach (var items in getNumber()) { Console.WriteLine(items); } }}

Output

3....5....

In the above example, we have created an iterator method getNumber() inside which we have used yield return.

Here, when getNumber() is called from foreach of Main(), the code inside getNumber() is executed until it reaches yield return.

When it reaches yield return, the current location of the code is preserved and the control goes back to the caller(i.e. foreach loop) and 3 is printed.

In the next iteration of foreach, the getNumber() method is called again. This time, getNumber() is executed from the preserved location of the code. This means,

Console.WriteLine("....");

gets executed and getNumber() resumes until it encounters another yield return and the same process continues till iterating over myList is completed.

Let's discuss the working of the above program with the help of an image.

Working of yield return

C# yield keyword (With Examples) (1)

1. foreach calls getNumber() - At first, the code inside the Main() function gets executed. Inside Main(), we have created a foreach loop that calls getNumber() method.

2. Inside getNumber(), myList is created.

3. Then, the foreach loop inside getNumber() starts iterating over myList. Notice the code,

if (num >= 0){ yield return num; // location of the code is preserved // so on the next iteration getNumber() is executed from here Console.WriteLine("....");}

When num = 3, num >= 0 returns True and yield return is encountered. Two operations occur:

  • pauses getNumber() and preserves the current location of the code
  • control goes back to the foreach loop (caller)

4. Control goes back to the caller - Here, the returned value 3 is printed and the next iteration of foreach begins.

In the next iteration, the getNumber() method is called again. In this call, getNumber() is resumed from the preserved location.

This means Console.WriteLine("...."); gets executed.

Now, in if block, num = 5 so num >= 0 is True. And again we encounter yield return.

5. Again, control goes back to the caller (inside foreach). Here, 5 is printed and foreach calls getNumber() in the next iteration.

The method resumes from the preserved location and prints ..... Since there are no other elements left in myList, iteration is stopped.

Frequently Asked Question

Why use yield keyword?

We have to create a temporary collection if we do not use yield return. For example,

using System;using System.Collections.Generic;class Program{ // define an iterator method static IEnumerable<int> getEven() { // create a list of integers List<int> myList = new List<int>() { 1, 2, 3, 4, 5 };

// create an empty temporary list List<int> tempList = new List<int>();

// iterate through myList foreach (var i in myList) { if (i % 2 == 0) { // adds i to temporary list tempList.Add(i); } } return tempList; } static void Main() { // display return values of getEven() foreach (var items in getEven()) { Console.WriteLine(items); } }}

Output

24

Here, we have created a temporary list tempList that stores the even numbers present inside myList.

Creating a temporary list slows down the computation and requires more memory when we are executing a large number of values.

yield break

The yield break ends an iterator ( list, array, etc) block. Let's take an example to understand it clearly.

using System;using System.Collections.Generic;class Program{ // define an iterator method static IEnumerable<string> getString() { // create a list of strings List<string> myList = new List<string> { "Sun", "Mon", "Tue" }; foreach (var day in myList) { if (day == "Mon") {

// terminates the iterator block after encountering "Mon" yield break;

} yield return day; } } static void Main() { // display return values of getString() foreach (var items in getString()) { Console.WriteLine(items); } }}

Output

Sun

Here inside the getString() method, notice

foreach (var day in myList){

if (day == "Mon") { // terminates the iterator block after encountering "Mon" yield break; }

yield return day;}

Here,

  • "Sun"=="Mon" is False so if block is not executed. Hence, the program executes yield return day and returns "Sun" to getString().
  • "Mon" == "Mon is True so if block is executed. Here, yield break is encountered and it ends the iterator block returning nothing.

Basically, if yield break is encountered, it indicates there are no more elements left in the collection.

Note: The yield break is different from break statement because break statement terminates the closest loop in normal method and yield break terminates the iterator method and transfers the control of the program to the caller.

yield break works just like return statement that returns nothing.

C# yield keyword (With Examples) (2024)

FAQs

How to use yield keyword in C#? ›

utilize the “yield” keyword in the function or property you wish to utilize as an iterator in C# to build an iterator block. The “yield” keyword tells the compiler that a method or property is an iterator and should return an iterator object when it appears in your code.

When not to use yield in C#? ›

You can't use the yield statements in:
  1. methods with in, ref, or out parameters.
  2. lambda expressions and anonymous methods.
  3. unsafe blocks. Before C# 13, yield was invalid in any method with an unsafe block. ...
  4. yield return and yield break can not be used in try, catch and finally blocks.
Jul 3, 2024

Is yield return more efficient? ›

Using yield return, you can read and process each record one by one, reducing the memory footprint significantly. This approach is not just memory efficient but also allows the consumer of this method to start processing data without waiting for the entire file to be read.

Is yield break necessary in C#? ›

No this is not necessary. It will work: public static IEnumerable<int> GetDiff(int start, int end) { while (start < end) { yield return start; start++; } // yield break; - It is not necessary. It is like `return` which does not return a value. }

What is an example of a yield? ›

For example, if there is a Treasury bond with a face value of $1,000 that matures in one year and pays 5% annual interest, its yield is calculated as $50 / $1,000 = 0.05 or 5%.

What are the advantages of yield in C#? ›

Using yield in C# can provide significant benefits, especially when working with large datasets. One of the main advantages of yield is that it allows for more efficient memory usage because data is generated on the fly instead of all at once. This can lead to better performance and fewer memory issues.

Why should I use yield? ›

If you want faster execution or computation over large datasets, yield is a better option. If you want to reduce memory consumption, you can use yield. It can be used to produce an infinite stream of data. You can set the size of a list to infinite, as it might cause a memory limit error.

What is the difference between yield and return in C#? ›

If you want the entire result at once, return is your reliable spell. If you prefer a magical, lazy approach that yields results on demand, then yield is your enchanting choice. In your coding adventures, consider the nature of your data and the iteration requirements.

Does Linq use yield? ›

You can use Yield Return within LINQ queries, enhancing the elegance and efficiency of your code. This synergy allows for dynamic data generation and transformation within the LINQ pipeline. Readable and Expressive: Both Select and Yield Return champion readability and expressiveness.

Is yield better than return? ›

Rate of return can be applied to nearly any investment while yield is somewhat more limited because not all investments produce interest or dividends. Mutual funds, stocks, and bonds are three common types of securities that have both rates of return and yields.

When was yield added to C#? ›

Yield was introduced in C# 2.0. Before its introduction, iterating over a collection required implementing a custom iterator using the IEnumerator interface.

What is the use of IEnumerable in C#? ›

This interface enables iterating over a collection. In other words, if something is an IEnumerable, you can mostly think of it like an array or a list. You can use a foreach statement to loop through it, you can use LINQ to map or reduce it in a hundred different ways, or you can explicitly cast it to an array with .

When to use thread yield in C#? ›

Yield(): If there is another thread ready to execute, then this gives away the current CPU core to that thread.

What is the use of task yield in C#? ›

Creates an awaitable task that asynchronously yields back to the current context when awaited.

What is the difference between yield break and return null? ›

“yield return null” does not exit the for loop, it just temporarily leave the coroutine and will continue just the next frame at the place where you left it. Cached_Timeline. Miss(); If you use yield break; the coroutine is terminated immediately.

What is the yield keyword in C# code project? ›

What is the yield keyword? The yield keyword is used for stateful iteration over a collection in a customized manner. The yield keyword informs the compiler that the method that contains it is an iterator block. In other words, yield will provide the next element or value from the sequence when iterating a sequence.

How to use using keyword in C#? ›

In C#, the using keyword has two purposes: The first is the using directive, which is used to import namespaces at the top of a code file. The second is the using statement. C# 8 using statements ensure that classes that implement the IDisposable interface call their dispose method.

How to use this keyword in C#? ›

To pass the object of the same class as a parameter to a method, the syntax will be: method_name(this); In the above syntax, 'this' keyword shows the object of the current class and method_name is the name of the method to be described.

Top Articles
50 Thanksgiving Dinner Recipes for the Feast of the Year
31 Delicious Easy Vegan Recipes to Start Your Plant-Based Journey
Tyler Sis 360 Louisiana Mo
Play FETCH GAMES for Free!
Part time Jobs in El Paso; Texas that pay $15, $25, $30, $40, $50, $60 an hour online
Prosper TX Visitors Guide - Dallas Fort Worth Guide
Bucks County Job Requisitions
Craigslist Nj North Cars By Owner
Urinevlekken verwijderen: De meest effectieve methoden - Puurlv
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Ap Chem Unit 8 Progress Check Mcq
Www.paystubportal.com/7-11 Login
How Many Cc's Is A 96 Cubic Inch Engine
Moparts Com Forum
Best Nail Salon Rome Ga
Yakimacraigslist
Equibase | International Results
Fraction Button On Ti-84 Plus Ce
Mccain Agportal
Https Paperlesspay Talx Com Boydgaming
67-72 Chevy Truck Parts Craigslist
[PDF] NAVY RESERVE PERSONNEL MANUAL - Free Download PDF
Nesb Routing Number
Aspenx2 Newburyport
Devotion Showtimes Near Regency Buenaventura 6
Violent Night Showtimes Near Amc Dine-In Menlo Park 12
1145 Barnett Drive
Local Collector Buying Old Motorcycles Z1 KZ900 KZ 900 KZ1000 Kawasaki - wanted - by dealer - sale - craigslist
JVID Rina sauce set1
Combies Overlijden no. 02, Stempels: 2 teksten + 1 tag/label & Stansen: 3 tags/labels.
Paradise Point Animal Hospital With Veterinarians On-The-Go
Experity Installer
Redding Activity Partners
About | Swan Medical Group
Lehpiht Shop
AP Microeconomics Score Calculator for 2023
Xemu Vs Cxbx
The Land Book 9 Release Date 2023
The 50 Best Albums of 2023
Dr. John Mathews Jr., MD – Fairfax, VA | Internal Medicine on Doximity
One Main Branch Locator
Craigslist Com Panama City Fl
Linkbuilding uitbesteden
Pain Out Maxx Kratom
Samsung 9C8
17 of the best things to do in Bozeman, Montana
Jimmy John's Near Me Open
Rubmaps H
Www Ventusky
Maurices Thanks Crossword Clue
28 Mm Zwart Spaanplaat Gemelamineerd (U999 ST9 Matte | RAL9005) Op Maat | Zagen Op Mm + ABS Kantenband
Law Students
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 5871

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.