Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
The elements of a C# array are accessed by enclosing the index expression between brackets [ and ] like this:
a[2] = b[3];In order to be able to use the same syntax to access the elements of a DynamicArray object, we define an indexer .
Program defines an indexer that provides both get and set accessor methods. The get accessor takes an index and returns the element found in the array at the given position. The set accessor takes an index and an object value and stores the value in the array at the given position.
Program: DynamicArray indexer.
Both accessors translate the given index by subtracting from it the value of the baseIndex field. In this way arbitrary subscript ranges are supported. Since the overhead of this subtraction is constant, the running times of the get and set accessors of the indexer are O(1).