Table of Contents
How does Yield Keyword work in C#?
Examples of Yield Keyword in C#
Example #1 – Method
Example #2 – Accessor
Example #3 – yield break
Rules
Advantages
Conclusion – Yield Keyword in C#

Yield Keyword in C#

Sep 03, 2024 pm 03:26 PM
c# c# tutorial

Yield is a contextual keyword in C#. Contextual keywords are those keywords in C# which are not reserved for the complete program. Rather they are reserved keywords for certain parts of the program where the keyword can be relevantly put to use. These keywords can be used as valid identifiers wherever their relevance does not convey any special meaning to the compiler.

The yield keyword indicates that the method or the accessor containing the keyword is an iterator method/accessor. An iterator method/accessor is one that does not return a single value. Rather, it is called in iterations and returns different values in each iteration.

Syntax

The syntax of the yield keyword is pretty simple. You simply need to specify the keyword before the return statement of the method or the accessor.

yield return <expression>;
Copy after login

OR

yield break;
Copy after login

These are the two implementations of the keyword. When used with a return statement, the yield keyword returns the next value calculated from the expression, until the exit condition of the expression is met. When used with the break keyword, the yield keyword breaks the iteration and program execution comes out of the method/accessor.

How does Yield Keyword work in C#?

  1. So, how does the keyword word in C#? What is the internal implementation of the keyword in the C# compiler? Let’s understand. The method containing the yield keyword can be consumed by an iterator loop such as foreach or LINQ query. Each iteration of the loop makes a call to the method. The code in the method is executed until a yield return or yield break statement is encountered.
  2. The current position of the execution in the method is retained and the next iteration continues from where it left off in the previous iteration.
  3. This was simple, wasn’t it? Let’s get into the technical implementation of the same. The method containing the yield keyword must always return an IEnumerable or IEnumerator. Whenever the compiler encounters the yield keyword, it knows that the method is consumed by an iterator. When the method is called, the compiler doesn’t execute the method body as it normally does.
  4. Rather it executes the method body and returns a compiled set of IEnumerables to the consuming iterator variable. On every call of the method, the compiler looks for a yield statement and pauses the execution at that statement. The next iteration of the loop continues the execution from the last paused location. This goes on till the exit condition of the loop or a yield break statement. To store the state information after each iteration, the compiler creates a state machine.

Examples of Yield Keyword in C#

Let us consider some examples:

Example #1 – Method

The example below generates the Fibonacci series using the yield keyword.

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
foreach (int ele in GetFibonacciSeries(10))
{
Console.Write(ele + "\t");
}
}
public static IEnumerable<int> GetFibonacciSeries(int x)
{
for (int a = 0, b = 0, c = 1; a < x; a++)
{
yield return b;
int temp = b + c;
b = c;
c = temp;
}
}
}
Copy after login

Yield Keyword in C#

Example #2 – Accessor

The following example uses the yield keyword with a get accessor.

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
foreach (Day day in new Days().DaysOfWeek)
{
Console.WriteLine("Day {0} of the week is {1}", day.DayOfWeek, day.DayName);
}
}
public static IEnumerable<int> Show(int x)
{
for (int a = 0, b = 0, c = 1; a < x; a++)
{
yield return b;
int temp = b + c;
b = c;
c = temp;
}
}
public class Days
{
public IEnumerable<Day> DaysOfWeek
{
get
{
yield return new Day{DayName = "Sunday", DayOfWeek = 1};
yield return new Day{DayName = "Monday", DayOfWeek = 2};
yield return new Day{DayName = "Tuesday", DayOfWeek = 3};
yield return new Day{DayName = "Wednesday", DayOfWeek = 4};
yield return new Day{DayName = "Thursday", DayOfWeek = 5};
yield return new Day{DayName = "Friday", DayOfWeek = 6};
yield return new Day{DayName = "Saturday", DayOfWeek = 7};
}
}
}
public class Day
{
public string DayName
{ get; set; }
public int DayOfWeek
{ get; set; }
}
}
Copy after login

Yield Keyword in C#

Example #3 – yield break

The following example demonstrates the use of the yield break statement. The iteration is terminated as soon as a number in the series is found or the max search limit is reached.

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int elementToFind = 21;
int maxElements = 100;
foreach (int ele in FindFibonacciNumber(elementToFind, maxElements))
{
Console.Write("Found the number " + elementToFind + " in Fibonacci series.");
}
}
public static IEnumerable<int> FindFibonacciNumber(int n, int max)
{
for (int a = 0, b = 0, c = 1; true; a++)
{
if (a > max)
{
Console.Write("Searched first " + max + " Fibonacci numbers. Element " + n + " not found");
yield break;
}
if (b == n)
{
yield return b;
yield break;
}
int temp = b + c;
b = c;
c = temp;
}
}
}
Copy after login

Yield Keyword in C#

If we change elementToFind 1234, the output will be –

Yield Keyword in C#

Rules

1) Each element must be returned one at a time using the yield return statement.
2) The return type must be an IEnumerable or IEnumerator.
3) You cannot use it in, ref, or out keywords with yield.
4) Yield keyword cannot be used with Lambda Expressions or Anonymous Methods.
5) A yield return statement cannot be inside a try-catch block. It can be inside a try-finally block.
6) A yield break statement cannot be inside a try-finally block. It can be inside a try-catch block.

Advantages

The yield keyword spares the need to create temporary collections. You need not create temporary collections to store the data before it is returned from the method. Also, the execution state of the method is retained and thus need not be explicitly stored in the code.

Conclusion – Yield Keyword in C#

We learned from this article that how to yield keyword is a very useful keyword in C#. It helps code complex problems with as few lines as possible and also makes the code easy to understand. This was an advanced level article on the C# journey. It is recommended to try and use the keyword in your code so that you get some hands-on practice.

The above is the detailed content of Yield Keyword in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

How to change the format of xml How to change the format of xml Apr 03, 2025 am 08:42 AM

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ​​such as Python. Be careful when modifying and back up the original files.

See all articles