views:

359

answers:

4

I've got the extremely unlikely and original situation of wanting to return a readonly array from my property. So far I'm only aware of one way of doing it - through the System.Collections.ObjectModel.ReadOnlyCollection<T>. But that seems somehow awkward to me, not to mention that this class loses the ability to access array elements by their index (added: whoops, I missed the indexer). Is there no better way? Something that could make the array itself immutable?

A: 

IEnumerable comes to mind.

epitka
Do you mean to cast my array to an IEnumerable and return that? That would then be even worse than the ReadOnlyCollection. First of all, anyone could easily cast it back to the array and modify it. Secondly it provides an even smaller subset of the functionality that arrays offer.
Vilx-
You can make this work just fine with an iterator (yield return statement).
Hans Passant
+1  A: 

You might want to implement the IEnumerable interface and overload the this[int] operator to deny access to it's setter

dbemerlin
Say what? In what way is it better than ReadOnlyCollection mentioned above?
Vilx-
+5  A: 

Use ReadOnlyCollection<T>. It is read-only and, contrary to what you believe, it has an indexer.

Arrays are not immutable and there is no way of making them so without using a wrapper like ReadOnlyCollection<T>.

Jeff Yates
+1  A: 

If you really want an array returned, but are afraid that the consumer of the array will mess with the internal data, just return a copy of the Array. Personally I still think ReadOnlyCollection<T> is the way to go, but if you REALLY want an array.....

BFree
Seems like a good idea, until you realise what class.MyArray[i] will do in a loop. Do that 1000 times and you have 1000 copies of the array!
RichardOD