I ' m trying to create a 2D array to store some the 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 the 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.
1 Answer
Actually trying to make the array -which was a reference type--this const would not affect Mutabil ity of its values @ all (you still can mutate any value within the array)-making the array readonly would make it com Pile, but not the desired effect either. Constant expressions has to being fully evaluated at compile time, hence the new operator was not allowed.
You might is looking forReadOnlyCollection<T>
For more see the corresponding Compiler Error CS0134:
Http://msdn.microsoft.com/en-us/library/ms228606.aspx
' Variable ' is of type ' type '. A const field of a reference type other than string can is initialized with null.
A Constant-expression is an expression, that can being fully evaluated at compile-time.
Because the only-to-create a non-null value of a reference-type is to apply the new operator, and Because the new Oper Ator is isn't permitted in a constant-expression,
The only possible value for constants of Reference-types and other than string is null.
If you encounter a const string array of trying to create a, the solution are to make the array readonly, and Init Ialize it in the
Constructor.
C #: Static readonly vs const?
Http://stackoverflow.com/questions/755685/c-static-readonly-vs-const
The ReadOnly keyword is different from the const keyword. A Const field can only is initialized at the declaration of the field.
A readonly field can be initialized either on the declaration or in a constructor. Therefore, readonly fields can has different values depending on the constructor used.
Also, while a const field was a Compile-time constant, the readonly field can be used to runtime constants as in the Follo Wing Example:
Http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=vs.100%29.aspx
public class Readonlytest { class SampleClass {public int x; Initialize a readonly field public readonly int y =; public ReadOnly int z; Public SampleClass () { //Initialize a readonly instance field z =; } Public SampleClass (int p1, int p2, int p3) { x = p1; y = p2; z = p3; } } static void Main () { SampleClass p1 = new SampleClass (one, +, +); OK Console.WriteLine ("P1:x={0}, Y={1}, Z={2}", p1.x, P1.y, p1.z); SampleClass P2 = new SampleClass (); p2.x =; OK Console.WriteLine ("P2:x={0}, Y={1}, Z={2}", p2.x, P2.y, p2.z); } } /* Output: p1:x=11, y=21, z=32 p2:x=55, y=25, z=24 */
A const field of a reference type other than string can is initialized with null Error [duplicate]