patterncsharpCritical
Declare a const array
Viewed 0 times
arrayconstdeclare
Problem
Is it possible to write something similar to the following?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };Solution
Yes, but you need to declare it
The reason is that
Declaring it
Depending on what it is that you ultimately want to achieve, you might also consider declaring an enum:
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 };Code Snippets
public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };public enum Titles { German, Spanish, Corrects, Wrongs };Context
Stack Overflow Q#5142349, score: 986
Revisions (0)
No revisions yet.