lucisferre

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult. —Sir Charles Antony Richard Hoare”

Yielding to Enumeration in C#

I just discovered the yield keyword and I can’t believe I hadn’t found it sooner. I became a huge fan of using LINQ from the moment I started using it and I am in the habit of passing and returning IEnumerable whenever possible.

Recently I had a problem where I was reading the lines of a CSV file using this code:

1
var csvdata = File.ReadAllLines(filename);

That seemed to work fine, but for some mysterious reason (that I still am uncertain of) it had problems reading the CSV file cleanly from a networked drive for some users. I have no idea why but I wanted to use something a bit more transparent.

A bit of googling turned up a solution that used a keyword I had never seen before:

1
2
3
4
5
6
7
8
9
private static IEnumerable<string> ReadLines(string path)
{
  using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open)))
  {
    string line;
    while ((line = reader.ReadLine()) != null)
      yield return line;
  }
}

I marveled at this yield keyword, it allows a method to return a result as IEnumerable, with delayed evaluation (each item in the result set is only returned when it is asked for) without having to implement a new IEnumerable class.

Anyways, nothing ground breaking, but a pretty handy tool nonetheless. Its been a while since I posted anything and I figured this was as good as anything else I’ve been thinking of posting, but nice and simple.

Comments