Yield Keyword in C#

王林
王林Original
2024-09-03 15:26:44354browse

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

OR

yield break;

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;
}
}
}

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; }
}
}

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;
}
}
}

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:
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
Previous article:C# Lambda ExpressionNext article:C# Lambda Expression