1

For some look-up table calculation, I have an array of values which I'd initially thought to declare in the C/C++ tradition like:

class MyClass
{
 UInt16[] _table =
  { ... };

In fact this is C code I am porting to C#. The issue is an array's contents can be modified even if the array is readonly. I can see there are .Net classes to provide immutable arrays but I am not sure:

  • If they can be initialized as easily/simply as a class member
  • How much performance hit this might give compared to an array; the whole LUT approach is done for performance in the first place.

Is this a case where I should just trust that nobody will modify the array contents, or is there a neat way to drop in an immutable version?

This is my current thinking:

    IList<UInt16> _table = Array.AsReadOnly(new UInt16[]
    { ... });
Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • 4
    A common way is `public IReadOnlyList Table { get; } = new[] { 1, 2, 3 };`. Note that consumers can get around the readonly-ness by casting, and it makes accessing the array a bit more expensive (interface method call instead of `ldelem`). If you need to avoid people casting, you can use a `ReadOnlyCollection` (interface method call + method call). There's also `ImmutableArray` (method call + `ldelem`, but no interface method calls) – canton7 Jan 20 '20 at 11:11
  • 2
    Does this answer your question? [What's the best way of creating a readonly array in C#?](https://stackoverflow.com/questions/2133616/whats-the-best-way-of-creating-a-readonly-array-in-c) – Johnathan Barclay Jan 20 '20 at 11:15
  • @canton7 should someone actively want to 'hack' the array contents then that's their deliberate choice, rather an simply a code bug. – Mr. Boy Jan 20 '20 at 11:16
  • 1
    @Mr.Boy That's the attitude I take, but some people care about being robust to that – canton7 Jan 20 '20 at 11:17
  • @JohnathanBarclay probably in the main though it doesn't seem to demonstrate initialization or any example. If people who know better decide this question offers no new detail, I'm happy they vote to close – Mr. Boy Jan 20 '20 at 11:18

0 Answers0