none
2d array initialization

    Question

  • Im currently trying to declare and initialize a bool[,]. I have attempted to do so with:

    public const bool[,] straightHorizontal = new bool[4,4] {
    {true, true, true, true}, 
    {false,false,false,false},
    {false,false,false,false},
    {true,true,true,true}};
    However this gives me an error:
    'Maze.GameConstants.straightHorizontal' is of type 'bool[*,*]'. A const field of a reference type other than string can only be initialized with null.

    On msdn: http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx it shows that you can declare and initialize a int[,] (note not string like my error claims) like so:

    int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
    I attempted this exact same code as above and got the same error that I got for bool:

    'Maze.GameConstants.array2D' is of type 'int[*,*]'. A const field of a reference type other than string can only be initialized with null.

    Can someone please tell me what I am doing wrong and a method of declaring and initializing a bool[,] in as few lines as possible?
    Sunday, April 05, 2009 3:41 PM

Answers

  • Change 'const" to "static".
    Mark the best replies as answers. "Fooling computers since 1971."
    • Marked as answer by Vilham Sunday, April 05, 2009 3:46 PM
    Sunday, April 05, 2009 3:45 PM
    Moderator

All replies

  • Change 'const" to "static".
    Mark the best replies as answers. "Fooling computers since 1971."
    • Marked as answer by Vilham Sunday, April 05, 2009 3:46 PM
    Sunday, April 05, 2009 3:45 PM
    Moderator
  •  const field of a reference type other than string can only be initialized with null.

    And you know why? Because the strings and only strings are always constant They are immutable. When you add a character to a string, this string is abandoned, a totally new string is created in memory and called the same name.

    AlexB
    Monday, April 06, 2009 12:15 AM
  •  const field of a reference type other than string can only be initialized with null.

    And you know why? Because the strings and only strings are always constant They are immutable. When you add a character to a string, this string is abandoned, a totally new string is created in memory and called the same name.

    AlexB
    The reason I didn't suspect the const problem was two fold. First I got it confused with FINAL, rather stupid of me. Secondly it was accepting int and float as consts, so I didn't understand why it wouldn't work for int[]. I assume this const thing only applies to arrays as far as only initializing strings.
    Monday, April 06, 2009 12:27 AM