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

The FetchNextLine method.

static IEnumerable<string> FetchNextLine(string fileName)
  StreamReader sr = new StreamReader(fileName);
  string line = "";
  string[] tokens = null;

  while ((line = sr.ReadLine()) != null)
    if (line.StartsWith("d@") == true)
      yield return line;
    else if (line.StartsWith("a@") == true) {
      string s = line.Replace('a', 'd');
      line = sr.ReadLine(); // advance to next line
      tokens = line.Split('@');
      s += tokens[1];
      yield return s;

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

comments powered by Disqus


.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events