Prev | Current Page 339 | Next

Jon Skeet

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

So:
?–  We??™ll make comparisons simple by constraining the range??™s type parameter T to
implement IComparable.
?–  We??™ll make the class abstract and require a GetNextValue method to be implemented,
which will be used during iteration.
?–  We won??™t worry about the idea of a range that can??™t be iterated over.
?–  We won??™t allow reverse ranges (so the end value must always be greater than or
equal to the start value).
?–  Start and end points will both be inclusive (so both the start and end points are
considered to be members of the range). One consequence of this is that we
can??™t represent an empty range.
The decision to make it an abstract class isn??™t as limiting as it possibly sounds??”it
means we??™ll have derived classes like Int32Range and DateTimeRange that allow you to
specify the ???step??? to use when iterating. If we ever wanted a more general range, we
could always create a derived type that allows the step to be specified as a Converter
delegate. For the moment, however, let??™s concentrate on the base type. With all the
requirements specified,8 we??™re ready to write the code.
6.3.3 Implementation using iterator blocks
With C# 2, implementing this (fairly limited) Range type is remarkably easy. The hardest
part (for me) is remembering how IComparable.CompareTo works. The trick I usually
use is to remember that if you compare the return value with 0, the result is the same
as applying that comparison operator between the two values involved, in the order
they??™re specified.


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