Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A const field of a reference type other than string can only be initialized with null Error [duplicate]

Tags:

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.

like image 754
nikhil Avatar asked Mar 31 '12 04:03

nikhil


1 Answers

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.

like image 148
BrokenGlass Avatar answered Oct 17 '22 08:10

BrokenGlass