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, Wash. He has worked on several Microsoft products including Azure and Bing. James can be reached at [email protected].

comments powered by Disqus

Featured

  • Decision Tree Regression from Scratch Using C#

    Dr. James McCaffrey of Microsoft Research says the technique is easy to tune, works well with small datasets and produces highly interpretable predictions, but there are also trade-off cons.

  • Visual Studio 'Tea & Technology' Video Miniseries Starts Next Week

    The goal of the miniseries is to provide an insider's snapshot look at some of the people who contribute to shaping the Visual Studio IDE every day.

  • Microsoft Releases OpenJDK 21 Build for Java Jockeys

    Microsoft today announced its "Microsoft Build of OpenJDK 21," taking advantage of new features and functionality in Java 21.

  • 'Dev Home' Update Leads Developer Goodies in AI-Powered Windows 11 Update

    Along with today's new AI-powered Windows 11 update come new goodies for developers, including a new edition of Dev Home, a preview offering described as a "control center" providing coding-focused features and functionality.

Subscribe on YouTube