Prev | Current Page 337 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

AddDays(1))
{
yield return day;
}
}
}
Now this has clearly just moved the original loop into the timetable class, but that??™s OK??”
it??™s much nicer for it to be encapsulated there, in a property that just loops through the
days, yielding them one at a time, than to be in business code that was dealing with those
days. If I ever wanted to make it more complex (skipping weekends and public holidays,
for instance), I could do it in one place and reap the rewards everywhere.
I thought for a while about making the timetable class implement IEnumerable
itself, but shied away from it. Either way would have worked, but it so happened
that the property led me toward the next step: why should the DateRange property
just be iterable? Why isn??™t it a fully fledged object that can be iterated over, asked
whether or not it contains a particular date, as well as for its start and end dates? While
we??™re at it, what??™s so special about DateTime? The concept of a range that can be
stepped through in a particular way is obvious and applies to many types, but it??™s still
surprisingly absent from the Framework libraries.
For the rest of this section we??™ll look at implementing a simple Range class (and
some useful classes derived from it). To keep things simple (and printable), we won??™t
make it as feature-rich as we might want??”there??™s a richer version in my open source
miscellaneous utility library7 that collects odds and ends as I occasionally write small
pieces of useful code.


Pages:
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349