How to declare an unwritten array in C #?

My code currently resembles this:

private static readonly int[] INTARRAY = {1, 2, 3};

This does not allow me to assign INTARRAYto a new instance int[]outside the static constructor, but it still allows me to assign individual elements int.
For instance:

INTARRAY[1] = 5;

How can I make this array fully read-only? This is an array of value types and is assigned by the array initializer in the declaration. How can I make these initial values ​​persist indefinitely?

+3
source share
3 answers

If it is an array, you cannot. But if you want it to be IList<int>, you can do:

private static readonly IList<int> INTARRAY = new List<int> {1, 2, 3}.AsReadOnly();
+9

, #, . , .

+1

If you are configured to use an array, you can write a simple wrapper class around the array using an element indexer.

+1
source

Source: https://habr.com/ru/post/1776577/


All Articles