0

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.

3

5 Answers 5

4

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;

Sign up to request clarification or add additional context in comments.

3 Comments

Except it would have to be static to be more const-like - and having a public static field which refers to a mutable data structure (the array) is generally a bad idea.
Please provide the .net internals e.g. why c# compiler does not allow above.
@RaviSharma I provide the documentation.what do you mean by .net Internals,I didn't write the c# compiler
1

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 = ...;

Comments

0

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;

2 Comments

That does not makes much sense. What the point of having constant null value?
This is for first use after you wrote null you identify const
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.