Demystifying the C# Yield-Return Mechanism: Listing 1.

Generating a 10-string sequence with yield-return.

static IEnumerable<string> ComputeNextString(int n)
  Random r = new Random(0);
  char[] charArray =
    new char[] { 'a','b','c','d','e','f','g','h' };

  for (int i = 0; i < n; ++i)
    int x = r.Next(0, charArray.Length);
    int y = r.Next(0, charArray.Length);
    char tmp = charArray[x];
    charArray[x] = charArray[y];
    charArray[y] = tmp;
    yield return new String(charArray);

About the Author

Dr. James McCaffrey works for Microsoft Research in Redmond, WA. James has worked on several key Microsoft products such as Internet Explorer and Bing. James can be reached at