Reputation: 21292
Currently, my code resembles this:
private static readonly int[] INTARRAY = {1, 2, 3};
This prevents me from assigning to INTARRAY
to a new instance of int[]
outside of the static constructor, but it still allows me to assign to the individual int
elements.
For example:
INTARRAY[1] = 5;
How can I make this array completely read-only? This is an array of value-types, and is assigned with an array initializer in the declaration. How can I make these initial values persist indefinitely?
Upvotes: 3
Views: 268
Reputation: 9653
If you're absolutely set on using an array, you could write a simple wrapper class around the array with a read-only indexer accessing the elements.
Upvotes: 1
Reputation: 5358
unfortunately, there is no builtin c# construct that provides this feature for arrays. Best solution is to use a List instead if it conforms with your business needs
Upvotes: 1
Reputation: 97676
If it's an array, you can't. But if you're willing for it to be an IList<int>
, you can do:
private static readonly IList<int> INTARRAY = new List<int> {1, 2, 3}.AsReadOnly();
Upvotes: 9