0

I have done some searching, but haven't found much. At the moment I am using:

class GlobalArrays
{
    public static string[] words = { "Easy", "Medium", "Hard" };
    public static Color[] backColors = { Color.LightGreen, Color.Orange, Color.Red };
}

Which works well, but I don't know if it is the correct way to do it. I've seen global variables done like this:

static class GlobalVars
{
    const string SOMETHING = "LOL";
}

Which is supposedly the Microsoft approved way of declaring namespace level constants, but when I tried that with arrays, it threw an error, saying they could only be of type string.

static class GlobalArrays
{
    public const string[] words = { "Easy", "Medium", "Hard" };
    public const Color[] backColors = { Color.LightGreen, Color.Orange, Color.Red };
}

The above code won't compile, and says they can only be initialized with null, because they are of a type that is not string.

1
  • Could you post the code that throws an error? Commented Dec 12, 2014 at 5:45

1 Answer 1

3

According to the compiler:

A const field of a reference type other than string can only be initialized with null.

I think this is about as close as you're going to get:

private static readonly string[] words = { "Easy", "Medium", "Hard" };
public static IReadOnlyCollection<string> Words
{
    get
    {
        return Array.AsReadOnly(words);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Note that the values of array elements can still be changed individually by any method that can access it.
@shree.pat18 That's why I've hidden it behind a ReadOnlyCollection.

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.