Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct syntax to initialize static array [duplicate]

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.

like image 481
Ali Padida Avatar asked Jan 23 '15 02:01

Ali Padida


2 Answers

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

public static string[] PAlphCodes = new string[] {
            "1593",
            "1604",
            "1740",
        };
like image 149
Kennedy Bushnell Avatar answered Sep 30 '22 11:09

Kennedy Bushnell


To expand upon what Kennedy answered -- you can also use

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

The reference manual has a listing of all the possible ways -- but the one Kennedy suggested -- and this method -- are probably the most common.

https://msdn.microsoft.com/en-us/library/aa287601(v=vs.71).aspx

like image 45
debracey Avatar answered Sep 30 '22 12:09

debracey