In c#, yield is a keyword, and it is useful to indicate that the method, operator, or property in which it appears is an iterator.
Following is the syntax of defining the yield keyword in c#.
In the above statements, the yield return
statement will return one element at a time, and the return type of yield keyword must always be IEnumerable or IEnumerator object of values. The yield break
statement is useful to end the iteration.
The yield return
or yield break
statements are not allowed to use in anonymous methods and in the methods that contain unsafe blocks.
The declaration of yield must meet the following requirements.
yield return
statement can use in the try block of try-finally statement.yield break
statement can use in try
or catch
block but not in finally
block.In c#, we can consume the iterator method that contains a yield return
statement either by using foreach loop or LINQ query.
In foreach loop, each iteration will call the iterator method, and the iterator method will return an expression when a yield return
statement is reached, and the current location of code is retained to restart the code execution from that location the next time the iteration method is called.
Following is the example of defining the yield return
statement in a method that’s inside of the foreach loop to return the required values.
If you observe the above example, we created Multiply() method with a yield return
statement that’s inside of for loop, and each iteration of the foreach loop will call the iterator method (Multiply) until it reaches yield return
statement and the return type of iterator method we used is IEnumerable of int.
Here, the iterator method (Multiply) will return the value after executing the yield return
statement and the current location of code is stored to restart the code execution from that location the next time when the iteration method is called.
For the first time, the Multiply method will execute all the lines of code, next time, the execution of the iterator body continues from the location (within for loop) where it left off, as shown below.
When we execute the above example, we will get the result as shown below.
This is how the yield keyword is useful to reduce the lines of code execution in c#.
Following are the important points which we need to remember about the yield keyword in c#.
yield
is a keyword, and it is useful to indicate that the method, operator, or property in which it appears is an iterator.yield return <expression>
and yield break
.yield return
or yield break
statements are not allowed to use in anonymous methods and in the methods that contain unsafe blocks.yield return
statement can use in the try block of try-finally statement.yield break
statement can be used in try or catch block but not in finally block.yield return
statement either by using a foreach loop or LINQ query.