12

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.

9
  • 2
    there's nothing built in for multidimensional arrays afaik Apr 18, 2012 at 21:14
  • Here are some answers from a similar question on StackOverflow - stackoverflow.com/questions/678379/… Apr 18, 2012 at 21:14
  • That's not very similar, @Scorpion-Prince.
    – Kirk Woll
    Apr 18, 2012 at 21:15
  • Perhaps a ReadOnlyCollection, each of whose elements is also a ReadOnlyCollection?
    – Mark Reed
    Apr 18, 2012 at 21:16
  • @Scorpion-Prince: and Op's says that he is aware that can implement kind of wrapper.
    – Tigran
    Apr 18, 2012 at 21:16

2 Answers 2

3

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.

2

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:

  • Create a wrapper class that exposes the properties of each element in the array as read only properties, so that they cannot be modified
  • Using primitive value types (like int)
  • Defeating the changes by returning a copy of the element in the private array instead of the original element in the private array, so that, the changes made to the object don't affect the original object in the array.

In other languages like C++ there are references and pointers to constant values, but this doesn't exist in C#.

1

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.