A simple range structure






1.36/5 (11 votes)
Mar 11, 2003
1 min read

51950

398
As its name suggests, it consists of two fields, the start and the end, which define inclusive bounds of a range the structure represents.
Introduction
In this article I'll present a simple data structure I had a need for. As its name suggests, it consists of two fields, the start and the end, which define inclusive bounds of a range the structure represents. The relation between bounds could exist as follows:
- The end is greater than the start
- The end is equal as the start meaning the range is consisted of only one representative
- The end is one less than the start meaning the range is empty
The structure contains following members:
Constructors
Range(int start, int end)
- constructs a range of given boundsRange(ICollection col)
- setup range to collection's lower and upper bounds
Properties
int start
- get or set lower boundint end
- get or set upper boundint mid
- get center pointint []
- obtain an element by a zero-based indexint Count
- get a number of elementsbool Empty
- returns true if range has no elements
Functions
void Set(int start, int end)
- redefines a rangebool Between(int value)
- returns true if value is within current rangeint Saturate(int value)
- forces value between current boundsvoid Offset(int o)
- moves range by ovoid Resize(int s)
- moves upper bound by s
Range
structure is declared as an ICollection
, meaning, it could
be used as a simple sequential number generator. For example:
foreach(int i in new Range(1, 10)) Console.Out.WriteLine(i);
Since the structure is consisted of only two fields which are mostly accessed in pair, I believe it was a reasonable choice to declare it as a value type.