public static IEnumerable YieldFun()
yield return 1;
yield return 2;
yield return 3;
static void Main(string args)
foreach (int i in YieldFun())
If you can tell me what the code above does, you understand how yield return works. If you can’t, read on……
In a C# program you can mark things as implementing the IEnumerable interface (to use this you need to have a using System.Collections; at the top of your program). This means the thing can be enumerated, i.e. it means that I can get a succession of objects from it.
The best way to work through something that can be enumerated is by using the foreach construction, as shown above. You’ve probably seen foreach when you’ve worked through items in a collection such as a List or an array. In the above code we are using foreach to work through the enumerable results that the YieldFun method returns.
The code inside YieldFun looks a bit scary. The yield return keyword combination is followed by the thing that you want to send back for this iteration. In this case I’m just returning a different number each time. What happens when the yield return is reached is that the method stops at that point, returns the result and then, when the foreach asks for the next value, the method wakes up and continues at the next statement. The result of the program is simply the sequence:
If you want to programmatically supply a sequence of items to a consumer then this is a great way to do it.