13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Real-life example: iterat<strong>in</strong>g over ranges173(<strong>in</strong>clud<strong>in</strong>g IDisposable). The language specification expla<strong>in</strong>s it <strong>in</strong> detail, but theupshot is that as a developer you don’t need to worry.The behavior of Current is odd—<strong>in</strong> particular, keep<strong>in</strong>g hold of the last item aftersupposedly mov<strong>in</strong>g off it could keep it from be<strong>in</strong>g garbage collected. It’s possible thatthis may be fixed <strong>in</strong> a later release of the <strong>C#</strong> compiler, though it’s unlikely as it couldbreak exist<strong>in</strong>g code. 6 Strictly speak<strong>in</strong>g, it’s correct from the <strong>C#</strong> 2 language specificationpo<strong>in</strong>t of view—the behavior of the Current property is undef<strong>in</strong>ed. It would benicer if it implemented the property <strong>in</strong> the way that the framework documentationsuggests, however, throw<strong>in</strong>g exceptions at appropriate times.So, there are a few t<strong>in</strong>y drawbacks from us<strong>in</strong>g the autogenerated code, but sensiblecallers won’t have any problems—and let’s face it, we’ve saved a lot of code <strong>in</strong> order tocome up with the implementation. This means it makes sense to use iterators morewidely than we might have done <strong>in</strong> <strong>C#</strong> 1. Our next section provides some sample codeso you can check your understand<strong>in</strong>g of iterator blocks and see how they’re useful <strong>in</strong>real life rather than just <strong>in</strong> theoretical scenarios.6.3 Real-life example: iterat<strong>in</strong>g over rangesHave you ever written some code that is really simple <strong>in</strong> itself but makes your projectmuch neater? It happens to me every so often, and it usually makes me happier than itprobably ought to—enough to get strange looks from colleagues, anyway. That sort ofslightly childish delight is particularly strong when it comes to us<strong>in</strong>g a new languagefeature <strong>in</strong> a way that is clearly nicer and not just do<strong>in</strong>g it for the sake of play<strong>in</strong>g withnew toys.6.3.1 Iterat<strong>in</strong>g over the dates <strong>in</strong> a timetableWhile work<strong>in</strong>g on a project <strong>in</strong>volv<strong>in</strong>g timetables, I came across a few loops, all ofwhich started like this:for (DateTime day = timetable.StartDate;day

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!