Arrays are a fast way to iterate through an unordered set of items, and it's often nice for them to be read-only. While exposing arrays with the `readonly' keyword is useless because the contents of the array can still be altered, a ReadOnlyCollection<T> wrapper solves this. The problem is it's 4 times slower than a plain array in tests I've done. (I know, returning a copy of the array would only take a performance hit once, but ideally I wouldn't want to waste CPU time on that either.)
I have noticed I can get the benefit of a read-only sanity-check while preserving the performance of a plain array with a class like this:
class ReadOnlyArray<T>
{
private readonly T[] array;
public ReadOnlyArray(T[] a_array)
{
array = a_array;
}
// read-only because no `set'
public T this[int i]
{ get { return array[i]; } }
public int Length
{ get { return array.Length; } }
}
The problem is I lose the convenience of the foreach() syntax. I.e. I have to iterate through it with a for(;;) loop in order to keep the performance. -- I used to write C code, where every loop was a for(;;). Maybe I've become spoiled. -- If I implement IEnumerable<T> then I get the same performance as ReadOnlyCollection<T>, and this class is useless.
Any idea how to achieve the perfect combination of all 3 goals: a read-only sanity check, no performance loss, and the convenient foreach() syntax?