The yield keyword was introduced in C# 2.0 (it is not currently available in VB.NET) and is useful for iteration. In iterator blocks it can be used to get the next value.
You implement it with a return statement, which will return the value to the enumerator object. You can use it to foreach over a collection. Example taken from the previous MSDN link:
// Display powers of 2 up to the exponent 8:
foreach (int i in Power(2, 8))
{
Console.Write("{0} ", i);
}
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
This produces the output: 2 4 8 16 32 64 128 256
Each iteration in the foreach block is given the next value from the IEnumerable Power method until no further results to yield are available.