C# 2.0 and the ‘yield’ keyword

Another nice addition to C# 2.0 is the yield keyword. Yield enables iterator blocks to provide values to an enumerated result, see the following example.

// yield-example.cs
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while(counter++ < exponent)
{
result = result * number;
yield return result;
}
}

static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach(int i in Power(2, 8))
Console.Write(“{0} “, i);
}
}

What does this mean in English? Essentially, iterator blocks can
implicitly create an array of results, which supports IEnumerable,
without having to declare an array data type and populating it.

The following line will signal the end of the iteration.

yield break;

6 thoughts on “C# 2.0 and the ‘yield’ keyword

  1. Sahil Malik

    And (VB.NET) that (VB.NET) other (VB.NET) language (VB.NET) we (VB.NET) won'(VB.NET) t (VB.NET) mention, (VB.NET) doesn’t support yield. Now isnt’ that crappy?(VB.NET)

  2. Trev

    Use the right tool for the job I say…. sure, custom iterators are more work to do in VB.Net, but just try interoperating with Excel using C#… lack of optional parameters and no late binding make it very difficult.

    (Note… I’m not advocating late binding… it’s just very handy when you’re dealing with different versions of the same library).

    Choose your tools wisely and without prejudice.

Comments are closed.