Why following is an Error in C#?
public const int[] test = { 1, 2, 3, 4, 5 };
Error : A const field of a reference type other than string can only be initialized with null.
Why following is an Error in C#?
public const int[] test = { 1, 2, 3, 4, 5 };
Error : A const field of a reference type other than string can only be initialized with null.
Error is self explanatory.Maybe, You are looking for this:
private static readonly int[] test = { 1, 2, 3, 4, 5 };
From MSDN:
A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and null.
Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants, as in this line: public static readonly uint l1 = (uint)DateTime.Now.Ticks;
The error message is already clear.
You can find the explanation in the C# Language Specifications under point Q.4 on side 313:
As described in §Constant expressions, a constant-expression is an expression that can be fully evaluated at compile-time. Since the only way to create a non-null value of a reference-type other than string is to apply the new operator, and since the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.
Best solution for a constant public collection of int would be
public static readonly ReadOnlyCollection<int> test = ...;
You have taken this error because you have to initiliaze test array firstly.Const types that you wrote must be initialized with null.I think correct definition is Public const int []=null;
null value?