Reputation: 2661
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?
Upvotes: 10
Views: 13675
Reputation: 887433
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[,] { ... }
.
Upvotes: 8
Reputation: 192467
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} }
};
Upvotes: 12