0

I need some help converting this multidimensional array from Java to c#:

int[] tileMap = new int[][] {
        {0, 1, 2, 3},
        {3, 2, 1, 0},
        {0, 0, 1, 1},
        {2, 2, 3, 3}
};

I'm working on implementing this Stackoverflow answer on generating isometric worlds in Unity. I know both Java and c#, but I lack the knowledge I need on c# multidimensional array to do the conversion.

I tried my only guess at converting it:

int[,] tileMap = new int[]{
        {0, 1, 2, 3},
        {3, 2, 1, 0},
        {0, 0, 1, 1},
        {2, 2, 3, 3}
};

But I can tell that it's not right, and it throws errors.

Thanks in advance for any help!

Community
  • 1
  • 1
Keith M
  • 1,199
  • 2
  • 18
  • 38

3 Answers3

1

Like this:

int[][] jagged = new int[][] {
    new int[] {0, 1, 2, 3},
    new int[] {3, 2, 1, 0},
    new int[] {0, 0, 1, 1},
    new int[] {2, 2, 3, 3}
};

Edit; the above supports jagged arrays. For non-jagged multidimensional arrays, from HungPV's comment:

var tileMap = new int[,] {
    {0, 1, 2, 3},
    {3, 2, 1, 0},
    {0, 0, 1, 1},
    {2, 2, 3, 3}
};

You use them differently, as well:

var res = jagged[0][1];
vs
var res = tileMap[0,1];

Rob
  • 26,989
  • 16
  • 82
  • 98
1

You are missing , in new int[]

Try like this

int[,] tileMap = new int[,]{
        {0, 1, 2, 3},
        {3, 2, 1, 0},
        {0, 0, 1, 1},
        {2, 2, 3, 3}
};
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • That did it :) I found it a few seconds ago from @HungPV's comment. Will accept when it lets me in 6 minutes – Keith M Sep 16 '15 at 02:19
  • A Java jagged array converts to a C# jagged array (as per Rob's answer). Don't know why so many seem to want to convert these to the C#-specific multidimensional array. – Dave Doknjas Sep 16 '15 at 04:10
  • @DaveDoknjas I found more info, so I marked Rob's answer as correct as I realized the multidimensional array was not right. I hadn't known of jagged arrays before, they seem quite useful :) – Keith M Sep 16 '15 at 04:46
0

You can initialize this way.

int[,] tileMap = new int[4, 4]{
        {0, 1, 2, 3},
        {3, 2, 1, 0},
        {0, 0, 1, 1},
        {2, 2, 3, 3}
};

Size is not mandatory, you can even use int[,]

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35