Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this array initialization incorrect?

Tags:

c#

.net

public byte[][,] Shapes = 
    {
        {
            {1,1}, 
            {1,1}
        }, 
        {
            {1}, 
            {1}, 
            {1}, 
            {1}
        },
        {
            {0,0,1},
            {1,1,1}
        }
    };

I get this error: "Array initializers can only be used in a variable or field initializer. Try using a new expression instead."

I could do this...

public class Shape
{
    public byte[][,] Shapes;

    public Shape()
    {
        Shapes = new byte[3][,];

        Shapes[0] = new byte[2, 2];
        Shapes[0][0, 0] = 1;
        Shapes[0][0, 1] = 1;
        Shapes[0][1, 0] = 1;
        Shapes[0][1, 1] = 1;

        Shapes[1] = new byte[1, 4];
        Shapes[1][0, 0] = 1;
        Shapes[1][0, 1] = 1;
        Shapes[1][0, 2] = 1;
        Shapes[1][0, 3] = 1;
    }
}

But that makes it very hard to add more shapes to my program.

Is my initializer wrong? And if I'm not allowed to do it this way, what's the easiest way to set it out?

like image 986
Kaije Avatar asked May 01 '11 16:05

Kaije


People also ask

What is the wrong way to initialization array?

Only square brackets([]) must be used for declaring an array.

What is array initialization with example?

int arrTwoDim[3][2] = {6, 5, 4, 3, 2, 1}; Example 8 defines a two-dimensional array of 3 sub-arrays with 2 elements each. The array is declared and initialized at the same time. The first element is initialized to 6, the second element to 5, and so on.

How do you initialize an array example?

An initializer list initializes elements of an array in the order of the list. For example, consider the below snippet: int arr[5] = {1, 2, 3, 4, 5}; This initializes an array of size 5, with the elements {1, 2, 3, 4, 5} in order.

How are arrays initialized in C++?

But, the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}. For example: int foo [5] = { 16, 2, 77, 40, 12071 };


2 Answers

This works for me:

  public byte[][,] Shapes = new byte[3][,]
    {
        new byte[,] { {1,1}, {1,1} },
        new byte[,] { {1}, {2}, {3}, {4} },
        new byte[,] { {0,0,1}, {1,1,1} }
    };
like image 165
Cheeso Avatar answered Oct 17 '22 09:10

Cheeso


Array initializer syntax ({ ... }) can only be used to initialize a field or variable.
To make arrays inside the outer array, you need to use normal array creation syntax.

Add new [] before the inner { ... } to create an implicitly-typed array.

Since you're dealing with bytes and multi-dimensional arrays, you may need to explicitly specify some of the types, by writing new byte[,] { ... }.

like image 43
SLaks Avatar answered Oct 17 '22 11:10

SLaks