outcome of each operation. This field can be examined after each operation to assess the
success or failure of the operation. (In Chapter 13, you will see a better way to handle errors
by using C#’s exception subsystem, but for now, using an error flag is an acceptable
accessor is shown here. It too prevents a boundary error.
element. Otherwise,
ErrFlag
. Recall that in an accessor method,
PART I
C h a p t e r 1 0 :
I n d e x e r s a n d P r o p e r t i e s
249
PART IPART I
implicit parameter that contains the value being assigned. You do not need to (nor can you)
declare it.
It is not necessary for an indexer to support both
get
and
set
. You can create a read-only
indexer by implementing only the
get
accessor. You can create a write-only indexer by
implementing only
set
.
Indexers Can Be Overloaded
An indexer can be overloaded. The version executed will be the one that has the closest
type-match between its parameter and the argument used as an index. Here is an example
that overloads the
FailSoftArray
indexer for indexes of type
double
. The
double
indexer
rounds its index to the nearest integer value.
// Overload the FailSoftArray indexer.
using System;
class FailSoftArray {
int[] a; // reference to underlying array
public int Length; // Length is public
public bool ErrFlag; // indicates outcome of last operation
// Construct array given its size.
public FailSoftArray(int size) {
a = new int[size];
Length = size;
}
// This is the int indexer for FailSoftArray.
public int this[int index] {
// This is the get accessor.
get {
if(ok(index)) {
ErrFlag = false;
return a[index];
} else {
ErrFlag = true;
return 0;
}
}
// This is the set accessor.
set {
if(ok(index)) {
a[index] = value;
ErrFlag = false;
}
else ErrFlag = true;
}
}
www.freepdf-books.com
250
P a r t I :
T h e C # L a n g u a g e
/* This is another indexer for FailSoftArray.
This index takes a double argument. It then
rounds that argument to the nearest integer index. */
public int this[double idx] {
// This is the get accessor.
get {
int index;
// Round to nearest int.
if( (idx - (int) idx) < 0.5) index = (int) idx;
else index = (int) idx + 1;
if(ok(index)) {
ErrFlag = false;
return a[index];
} else {
ErrFlag = true;
return 0;
}
}
// This is the set accessor.
set {
int index;
// Round to nearest int.
if( (idx - (int) idx) < 0.5) index = (int) idx;
else index = (int) idx + 1;
if(ok(index)) {
a[index] = value;
ErrFlag = false;
}
else ErrFlag = true;
}
}
// Return true if index is within bounds.
private bool ok(int index) {
if(index >= 0 & index < Length) return true;
return false;
}
}
// Demonstrate the fail-soft array.
class FSDemo {
static void Main() {
FailSoftArray fs = new FailSoftArray(5);
// Put some values in fs.
for(int i=0; i < fs.Length; i++)
fs[i] = i;
// Now index with ints and doubles.
Console.WriteLine("fs[1]: " + fs[1]);
www.freepdf-books.com