41

Possible Duplicate:
Declare a Const Array

I need an array of const strings in the class. Something like

public class some_class_t
{
    public const string[] names = new string[4]
    {
        "alpha", "beta", "gamma", "delta"
    };
}

But this code causes an error:

A constant 'names' of reference type 'string[]' can only be initialized with null.

What should I do?

1
  • 4
    Arrays are mutable. They can't be constant unless they're null. Commented Dec 28, 2012 at 0:48

1 Answer 1

78

Declare it as readonly instead of const:

public readonly string[] names = { "alpha", "beta", "gamma", "delta" };
Sign up to request clarification or add additional context in comments.

7 Comments

And declare it static so I would use public readonly string[] names = { "alpha", "beta", "gamma", "delta" };
What mike nelson meant to type was "public static readonly string[] names = { "alpha", "beta", "gamma", "delta" };
Why is this accepted? while question was about const not readonly...
Anyone know how you could actually do it as a const? rather than a readonly? I would like to reference it from my own custom attribute on a class property, and only a const will do. Thanks
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.