What is the underlying implementation of C# yield?

In C#, the keyword “yield” is used to create iterators. By using the “yield” keyword, a method can return a collection that can be iterated through without needing to build the entire collection immediately.

The principle of implementing yield is as follows:

  1. When a method containing the `yield` keyword is called, the code inside the method will not be executed immediately, instead it will return an iterator object that implements the IEnumerable or IEnumerator interface.
  2. When the MoveNext() method of the iterator object is called, the code inside the method starts to execute. The code will continue to run until it encounters the yield keyword, which will return the current value to the caller and pause the execution of the code.
  3. When the MoveNext() method is called next time, the code will resume from where it last paused and continue until it encounters the next yield keyword or the method finishes.
  4. When the Reset() method of the iterator object is called, the code will return to its initial state, and the next time the MoveNext() method is called, it will be executed again.
  5. When the iterator object reaches the end of the collection, the MoveNext() method returns false, indicating the end of the iteration.

In this way, using the yield keyword makes it easy to create a lazily loaded collection. When iterating over collection elements, only necessary code will be executed, reducing memory overhead and the time complexity of computations.

bannerAds