Search code examples
c#arraysnullreferenceexceptioninitializer

Correct syntax to initialize static array


I have following code definig an array

 public class PalphabetsDic
 {
     public static string[] PAlphCodes = new string[3] {
         PAlphCodes[0] = "1593",
         PAlphCodes[1] = "1604",
         PAlphCodes[2] = "1740",
     };
 }

When I use this array

var text = PalphabetsDic.PAlphCodes[1]

Gives error:

The type initializer for 'Dota2RTL.PalphabetsDic' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object.

Please can someone help me on this?

Note that What is a NullReferenceException, and how do I fix it? covers arrays, but PAlphCodes = new string[3] should be setting it up to be not null.


Solution

  • When initializing the way you are you don't need to index the values:

    public static string[] PAlphCodes = new string[] {
                "1593",
                "1604",
                "1740",
            };