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?

Community
  • 1
  • 1
Newbee
  • 1,032
  • 1
  • 11
  • 27

1 Answers1

77

Declare it as readonly instead of const:

public readonly string[] names = { "alpha", "beta", "gamma", "delta" };
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • more details available at [http://stackoverflow.com/a/5142378/1080355](http://stackoverflow.com/a/5142378/1080355) – VSB Nov 18 '13 at 07:33
  • 3
    And declare it `static` so I would use `public readonly string[] names = { "alpha", "beta", "gamma", "delta" };` – mike nelson Aug 06 '16 at 23:08
  • 4
    What mike nelson meant to type was "public static readonly string[] names = { "alpha", "beta", "gamma", "delta" }; – BoiseBaked Aug 22 '18 at 20:54
  • 3
    Why is this accepted? while question was about `const` not `readonly`... – Yousha Aleayoub Apr 16 '20 at 19:50
  • Because it does what the OP intended (supposedly). You have to have the ability to recognize that, especially as a developer. – Jens Mander Jun 01 '20 at 20:00
  • 1
    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 – z0mbi3 Nov 24 '22 at 19:07
  • Link for "Since C# 6 you can write it like: public static string[] Titles => new string[] { "German", "Spanish", "Corrects", "Wrongs" }; " https://stackoverflow.com/a/38844044/2641380 – SHS May 24 '23 at 06:30