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, WA. James has worked on several key Microsoft products such as Internet Explorer and Bing. James can be reached at