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
| |
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 | |
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.