Reputation: 27343
Is there any established way of returning a read-only 2-d array in C#?
I know ReadOnlyCollection
is the right thing to use for a 1-d array, and am happy to write my own wrapper class that implements a this[] {get}
. But I don't want to reinvent the wheel if this wheel already exists.
Upvotes: 13
Views: 4875
Reputation: 39004
There's only one way to simulate this.
You need to create your own class, with a private array.
The most similar implementation of an array is an indexer:
The '10.8' link shows the simulation of a bidimensional array.
If you implement the indexer only with a getter, the user can only read the elements, but not write them. However, if each element is an object (reference type) you can't prevent the modification of the accessed objects properties.
However, there are several ways of simulating "read-only" objects:
int
)In other languages like C++ there are references and pointers to constant values, but this doesn't exist in C#.
Upvotes: 2
Reputation: 62248
Unfortunately there is no any built-in implementation to handle a case you ask for. But a simple implementation on your own, shouldn't be something difficult.
The only think, I hope you aware of it, that you will do is a readonly collection, but not elements inside that collection.
Hope this helps.
Upvotes: 3