C# yield Example - Dot Net Perls (2024)

HomeC#

yield Example

This page was last reviewed on Jan 16, 2024.

Dot Net Perls

Yield. This C# keyword interacts with the foreach-loop. It is a contextual keyword: yield is a keyword only in certain statements. It can make loops clearer and simpler to write.

C# yield Example - Dot Net Perls (1)

Yield allows each iteration in a foreach-loop to be generated only when needed. In this way (by enabling lazy evaluation) it can improve performance.

An example. We use yield in methods that return the type IEnumerable (without any angle brackets), or the type IEnumerable with a type parameter in the angle brackets.

Info We reference the System.Collections namespace for the first version, and the System.Collections.Generic namespace for the second.

Part 1 In the part of the foreach-loop following the "in" keyword, there is a method call to ComputePower.

foreach

Part 2 ComputePower() receives 2 parameters. It returns an IEnumerable int type, which we can use in a foreach-loop.

C# yield Example - Dot Net Perls (2)

using System;using System.Collections.Generic;public class Program{ static void Main() { // Part 1: compute powers of two with the exponent of 30. foreach (int value in ComputePower(2, 30)) { Console.WriteLine(value); } } public static IEnumerable<int> ComputePower(int number, int exponent) { // Part 2: continue loop until the exponent count is reached. // ... Yield the current result. int exponentNum = 0; int numberResult = 1; while (exponentNum < exponent) { // Multiply the result. numberResult *= number; exponentNum++; // Return the result with yield. yield return numberResult; } }}

248163264128256512102420484096819216384327686553613107226214452428810485762097152419430483886081677721633554432671088641342177282684354565368709121073741824

Internals. The C# code you have that uses yield is not directly executed by the runtime. Instead, the C# compiler transforms that code before the runtime ever occurs.

Tip The compiler-generated class, marked with CompilerGenerated, instead uses several integral types.

Result We see an entire class that is similar to how your code would look if you manually implemented the interfaces.

Info The punctuation characters allow the compiler to ensure no naming conflicts will occur with your code.

// Nested Types[CompilerGenerated]private sealed class <ComputePower>d__0 : IEnumerable<int>, IEnumerable, IEnumerator<int> // ...{ // Fields private int <>1__state; private int <>2__current; public int <>3__exponent; public int <>3__number; private int <>l__initialThreadId; public int <exponentNum>5__1; public int <numberResult>5__2; public int exponent; public int number; // Methods [omitted]}

Benchmark, yield. Is yield return fast? Or does it incur a significant performance loss? Yield return does have some overhead, but if you need its advanced features it can be faster.

Version 1 This version of the code uses a foreach-loop over an array and multiplies each element.

Version 2 Here we use a yield return method (one that returns IEnumerable) to perform the multiplication.

Result The version that uses yield return runs many times slower. For simple things, avoid yield return for top speed.

using System;using System.Collections.Generic;using System.Diagnostics;class Program{ const int _max = 1000000; static void Main() { int[] numbers = { 10, 20, 30, 40, 50 }; var s1 = Stopwatch.StartNew(); // Version 1: use foreach with array. for (int i = 0; i < _max; i++) { if (Method1(numbers) != 300) { throw new Exception(); } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use foreach with yield keyword. for (int i = 0; i < _max; i++) { if (Method2(numbers) != 300) { throw new Exception(); } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } static int Method1(int[] numbers) { // Sum with simple statements. int sum = 0; foreach (int number in numbers) { sum += number * 2; } return sum; } static int Method2(int[] numbers) { // Use yield return to get multiplied numbers and then sum those. int sum = 0; foreach (int number in GetNumbers(numbers)) { sum += number; } return sum; } static IEnumerable<int> GetNumbers(int[] numbers) { // Return all numbers multiplied. foreach (int number in numbers) { yield return number * 2; } }}

3.84 ns inline expression50.68 ns yield return

Notes, IEnumerable. IEnumerable is an interface. It describes a type that implements the internal methods required for using foreach-loops.

IEnumerable

Return. Yield return is similar to a return statement, followed by a "goto" to the yield statement in the next iteration of the foreach-loop.

returngoto

Yield benefits. Suppose we have a large (or even infinite) set of items (like prime numbers, or species of beetles). Yield can provide a benefit here.

Tip We can just loop over items from the infinite set until we encounter one that matches our requirements.

And This reduces memory, reduces loading time of the set, and can also result in cleaner C# code.

Summary. We examined the yield return pattern. The yield keyword is contextual—it only has special significance in some places. It helps simplify foreach-loops.

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Jan 16, 2024 (edit).

HomeChanges

© 2007-2024 Sam Allen.

C# yield Example - Dot Net Perls (2024)

FAQs

What is yield in C# with example? ›

The yield keyword in C# is used to create an iterator method, which allows the programmer to loop through a collection of items, one at a time. It allows the code inside the iterator method to "yield" each item in the collection, one at a time, rather than returning the entire collection all at once.

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.

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 the difference between yield and IEnumerable in C#? ›

IEnumerable is the return type from an iterator. An iterator is a method that uses the yield return keywords. yield return is different from a normal return statement because, while it does return a value from the function, it doesn't “close the book” on that function.

What is a yield example? ›

Yield is often expressed as a percentage, based on either the investment's market value or purchase price. For example, let's say bond A has a $1,000 face value and pays a semiannual coupon of $10. Over one year, bond A yields $20, or 2%.

What is the benefit 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.

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

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.

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 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.

Is IEnumerable faster than list C#? ›

Performance: IEnumerable generally performs better in terms of performance when used with LINQ queries and foreach loops because it prevents needless memory allocation and copying whereas Lists are more effective since they give you direct access to the items and are used frequently when index-based access and ...

Why we use IEnumerable instead of list in C#? ›

In this article, we've looked at the basics of IEnumerable and List in C#. We've seen that while both can be used to store collections of items, they have different characteristics and uses. IEnumerable is best for read-only collections, while List is better for collections that can be modified.

Why is multiple enumeration bad? ›

If the enumeration operation itself is expensive, for example, a query into a database, multiple enumerations would hurt the performance of the program. If the enumeration operation has side effects, multiple enumerations might result in bugs.

What is yield used for? ›

Yield is return on investment, expressed as a percentage. In stocks, dividend yield is the total annual share of a company's profit that is returned to its shareholders. In bonds, yield is the interest that is paid to bondholders in return for their investment. In mutual funds, yield is the net income of the fund.

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 and return? ›

A return in finance refers to the amount of money gained or lost from an investment over time. A yield in finance signifies the potential earnings that an investment may provide over time.

Top Articles
Conan Exiles a Guide to Cooking, Potions, Elixirs & Books
Mochi Marijuana Strain Information- Kif
Funny Roblox Id Codes 2023
Golden Abyss - Chapter 5 - Lunar_Angel
Www.paystubportal.com/7-11 Login
Joi Databas
DPhil Research - List of thesis titles
Shs Games 1V1 Lol
Evil Dead Rise Showtimes Near Massena Movieplex
Steamy Afternoon With Handsome Fernando
Which aspects are important in sales |#1 Prospection
Detroit Lions 50 50
18443168434
Newgate Honda
Zürich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Grace Caroline Deepfake
978-0137606801
Nwi Arrests Lake County
Justified Official Series Trailer
London Ups Store
Committees Of Correspondence | Encyclopedia.com
Pizza Hut In Dinuba
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
How Much You Should Be Tipping For Beauty Services - American Beauty Institute
Free Online Games on CrazyGames | Play Now!
Sizewise Stat Login
VERHUURD: Barentszstraat 12 in 'S-Gravenhage 2518 XG: Woonhuis.
Jet Ski Rental Conneaut Lake Pa
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Ups Print Store Near Me
C&T Wok Menu - Morrisville, NC Restaurant
How Taraswrld Leaks Exposed the Dark Side of TikTok Fame
University Of Michigan Paging System
Dashboard Unt
Access a Shared Resource | Computing for Arts + Sciences
Speechwire Login
Healthy Kaiserpermanente Org Sign On
Restored Republic
3473372961
Craigslist Gigs Norfolk
Moxfield Deck Builder
Senior Houses For Sale Near Me
D3 Boards
Jail View Sumter
Nancy Pazelt Obituary
Birmingham City Schools Clever Login
Thotsbook Com
Funkin' on the Heights
Vci Classified Paducah
Www Pig11 Net
Ty Glass Sentenced
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 5363

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.