C# questions & answers: can you declare a constant array of integers?

Posted: (EET/GMT+2)

 

Today's blog post is a quick Q&A session about the C# language and constant values.

In C#, if you try to declare a constant within a class like this:

public const List MyIds = new List(new int[] { 123, 234, 345 });

...you will get the following compiler error:

Error CS0133
The expression being assigned to 'MyConstants.MyIds' must be constant

Shortly put, C# does not support constant array declarations, as these must be initialized at runtime instead of compile time.

However, you can get pretty close by declaring the field as a "static readonly" field. However, this doesn't stop the user of the value to change the contents of the array values, just the array as a whole. If you want to protect against this by accident, you can use the collection type "IReadOnlyList" from the System.Collections.Generic namespace.

Here's an example:

public const IReadOnlyList MyIds =
    new List(new int[] { 123, 234, 345 });

This is pretty close to having a real, constant-values array.

Hope this helps!