What is the Yield keyword and use of in C#?
Ashish Saxena
Select an image from your device to upload
I found below link on asked topic, but could not digest it, Please help if you have better explanation and real time example
https://www.c-sharpcorner.com/UploadFile/5ef30d/understanding-yield-return-in-C-Sharp/
-“Yield keyword helps us to do custom stateful iteration over .NET collections.”
-“Yield” keyword will return control to the caller, the caller will do his work and re-enter the function from where it had left and continue iteration from that point onwards.
-There are two scenarios where “yield” keyword is useful:- Customized iteration through a collection without creating a temporary collection. Stateful iteration.
-yield keyword indicates that the method, operator, or property in which it appears is an iterator.
-The yield keyword statement can be declared like yield return <;expression>; and yield break.
-The return type of yield must be an IEnumerable or IEnumerator object of values.
-The yield return or yield break statements are not allowed to be used in anonymous methods and in the methods that contain unsafe blocks.
-In c#, the yield return statement can be used in the try block of the try-finally statement.
-The yield break statement can be used in try or catch block but not in finally block.
-We can consume the iterator method that contains a yield return statement either by using a foreach loop or LINQ query.