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;
In C# the public const fields can either be null or strings. If you make the field read only:
// public readonly int[] test = { 1, 2, 3, 4, 5 };
Then it should be ok for you to run this code
For arrays in .NET, you can change their items. You can still do the following:
test[3] = 7;
So const array is not truly constant, that is why it is disallowed. The only allowed reference types as constants are immutable ones, and they are just string and null in .NET.