Ashish Saxena
What is the Yield keyword and use of in C#?

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/

By Ashish Saxena in .NET on Jul 19 2023
  • Jainexi Parmar
    Aug, 2023 6

    -“Yield keyword helps us to do custom stateful iteration over .NET collections.”

    • It moves control of the program to and from between caller and the collection.

    -“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.

    • 1
  • Onyedika Ilodibe
    Sep, 2023 6

    A yield keyword is used with an iterator method. it enables your to iterate over a collection one after the other without loading the entire collection into memory

    • 0
  • Tasadduq Burney
    Aug, 2023 15

    The yield keyword in C# is used in combination with an iterator method to create an iterator, which allows you to iterate over a collection of items without needing to load the entire collection into memory at once. It's particularly useful for working with large sets of data or when you want to generate values on-the-fly without precomputing them all.

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS