Understanding C#'s yield
Keyword for Efficient Iteration
Introduced in C# 2.0, the yield
keyword significantly streamlines imperative iteration. Consider this example, illustrating its use in creating an IEnumerable<T>
:
IEnumerable<object> FilteredList() { foreach(object item in FullList) { if(IsItemInPartialList(item)) yield return item; } }
This function doesn't build a complete list in memory. Instead, it returns an iterator. Each time the foreach
loop in the calling code requests the next item, the FilteredList()
function resumes execution from where it left off, evaluating the next item
and returning it only if the condition is met.
Let's examine a simpler example:
public void Consumer() { foreach(int i in Integers()) { Console.WriteLine(i); } } public IEnumerable<int> Integers() { yield return 1; yield return 2; yield return 4; yield return 8; yield return 16; yield return 16777216; }
Debugging this code reveals that Integers()
doesn't execute fully at once. It executes only until it hits a yield return
, returning a single value. The next iteration of the foreach
loop in Consumer()
causes Integers()
to resume, continuing from the next yield return
.
Key benefits of using yield
:
IEnumerable
and IEnumerator
, resulting in cleaner, more concise code.The above is the detailed content of How Does the C# `yield` Keyword Simplify Imperative Iteration?. For more information, please follow other related articles on the PHP Chinese website!