Declare a const array Declare a const array arrays arrays

Declare a const array


Yes, but you need to declare it readonly instead of const:

public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };

The reason is that const can only be applied to a field whose value is known at compile-time. The array initializer you've shown is not a constant expression in C#, so it produces a compiler error.

Declaring it readonly solves that problem because the value is not initialized until run-time (although it's guaranteed to have initialized before the first time that the array is used).

Depending on what it is that you ultimately want to achieve, you might also consider declaring an enum:

public enum Titles { German, Spanish, Corrects, Wrongs };


You can declare array as readonly, but keep in mind that you can change element of readonly array.

public readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };...Titles[0] = "bla";

Consider using enum, as Cody suggested, or IList.

public readonly IList<string> ITitles = new List<string> {"German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();


You can't create a 'const' array because arrays are objects and can only becreated at runtime and const entities are resolved at compile time.

What you can do instead is to declare your array as "readonly". This has thesame effect as const except the value can be set at runtime. It can only beset once and it is thereafter a readonly (i.e. const) value.