21

I'm trying to create a 2D array to store some values that don't change like this.

const int[,] hiveIndices = new int[,] {
{200,362},{250,370},{213,410} , 
{400,330} , {380,282} , {437, 295} ,
{325, 405} , {379,413} ,{343,453} , 
{450,382},{510,395},{468,430} ,
{585,330} , {645,340} , {603,375}
};

But while compiling I get this error

hiveIndices is of type 'int[*,*]'. 
A const field of a reference type other than string can only be initialized with null.

If I change const to static, it compiles. I don't understand how adding the const quantifier should induce this behavior.

nikhil
  • 8,925
  • 21
  • 62
  • 102

1 Answers1

43

Actually you are trying to make the array - which is a reference type - const - this would not affect mutability of its values at all (you still can mutate any value within the array) - making the array readonly would make it compile, but not have the desired effect either. Constant expressions have to be fully evaluated at compile time, hence the new operator is not allowed.

You might be looking for ReadOnlyCollection<T>

For more see the corresponding Compiler Error CS0134:

A constant-expression is an expression that can be fully evaluated at compile-time. Because the only way to create a non-null value of a reference-type is to apply the new operator, and because the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • Actually creating a readonly 2d array will require writing a wrapper for it because `AsReadOnly` only supports one-dimensional, zero-based arrays: for more reading see http://stackoverflow.com/questions/5079970/storing-2-dimensional-ints-as-readonly-const-in-separate-class-whilst-keeping-no – BrokenGlass Mar 31 '12 at 04:55
  • you mean that I have downvoted coz my answer is not the best one? – ABH Mar 31 '12 at 05:55
  • 1
    I didn't downvote your answer, but probably yes - your answer will make the code *compile* but you can still mutate the elements in the array, which is what OP wants to guard against – BrokenGlass Mar 31 '12 at 06:00
  • 1
    Okey, thanks. it would be too chatty but I'm asking as a new user. Should I remove my answer or should I updated it? What's the best practice? – ABH Mar 31 '12 at 06:02
  • 1
    At this point if you don't have a better answer you can just delete it and you will get back the negative reputation – BrokenGlass Mar 31 '12 at 06:05