Home >Backend Development >C#.Net Tutorial >Yield Keyword in C#
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.
Let us consider some examples:
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; } } }
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; } } }
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; } } }
If we change elementToFind 1234, the output will be –
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.
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.
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!