No, this is not a post about the current state of the worlds financial industries, instead it is about one of the lesser known C# features called “yield” that can be used to create dynamic collections. It is one of the more disputed features of C# because it is “not really object oriented” and more of a hack than anything else. While this is most likely true, I find it hard to argue its usability. See for yourself.
The yield return and yield break keywords are only valid in methods and properties with a IEnumerable return type. They can be used to generate object enumerators “on the fly” without the need to explicitly create a temporary container. yield return obj; will add obj to the imaginary collection and yield break; will terminate the enumeration. The example code below shows how to use the yield mechanism to iterate over a dynamically generated collection.
public IEnumerable PowersOfTwo(int upperBound)
{
int current = 1;
while (current < upperBound)
{
yield return current;
current *= 2;
}
yield break;
}
public void ShowPowersOfTwo()
{
foreach (int num in PowersOfTwo(1000000))
{
Console.WriteLine(num);
}
}
The output of which would of course be
1 2 4 8 16 ...