Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way of creating a readonly array in C#?

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?

like image 573
Vilx- Avatar asked Jan 25 '10 16:01

Vilx-


3 Answers

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>.

Note that creating a ReadOnlyCollection<T> wrapper is an O(1) operation, and does not incur any performance cost.

Update
Other answers have suggested just casting collections to the newer IReadOnlyList<T>, which extends IReadOnlyCollection<T> to add an indexer. Unfortunately, this doesn't actually give you control over the mutability of the collection since it could be cast back to the original collection type and mutated.

Instead, you should still use the ReadOnlyCollection<T> (the List<T> method AsReadOnly(), or Arrays static method AsReadOnly() helps to wrap lists and arrays accordingly) to create an immutable access to the collection and then expose that, either directly or as any one of the interfaces it supports, including IReadOnlyList<T>.

like image 141
Jeff Yates Avatar answered Nov 14 '22 09:11

Jeff Yates


.NET Framework 4.5 introduced IReadOnlyList<T> which extends from IReadOnlyCollection<T> adding T this[int index] { /*..*/ get; }.

You can cast from T[] to IReadOnlyList<T>. One advantage of this is that (IReadOnlyList<T>)array understandably equals array; no boxing is involved.

Of course, as a wrapper is not being used, (T[])GetReadOnlyList() would be mutable.

like image 22
Warty Avatar answered Nov 14 '22 09:11

Warty


From .NET Framework 2.0 and up there is Array.AsReadOnly which automatically creates a ReadOnlyCollection wrapper for you.

like image 10
N8allan Avatar answered Nov 14 '22 09:11

N8allan