📎 Webclip
Muhammad Waseem (@mwaseemzakir) on X
The post explains that yield is used for custom stateful iteration over .NET collections. It contrasts building a full list and returning it with letting the caller consume values during iteration, and says yield basically returns an IEnumerable. It also notes that C# 8 adds IAsyncEnumerable and that yield works lazily, so values are not retrieved until the collection is iterated or materialized with ToList().
Reading notes#
yield returnandyield breakare presented as the key forms of the keyword.- The example focuses on checking even numbers between 1 and 1000.
- One approach stores all results in a list before returning them.
- Another approach keeps iterating and reports numbers to the caller as it goes.
yieldis described as useful for that second approach.- Methods with
ref,in, oroutparameters are said not to allowyield. - Lambda expressions and anonymous methods are said not to contain
yield. - The post says the sequence is only retrieved when iterated with a
forloop or whenToList()is used.
