Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

DynamicArray Indexers

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 gif 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.

   program2744
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).


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.