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?
Only square brackets([]) must be used for declaring an array.
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.
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.
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 };
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} }
};
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 byte
s and multi-dimensional arrays, you may need to explicitly specify some of the types, by writing new byte[,] { ... }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With