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!

1

3 Answers 3

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];

Sign up to request clarification or add additional context in comments.

Comments

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}
};

3 Comments

That did it :) I found it a few seconds ago from @HungPV's comment. Will accept when it lets me in 6 minutes
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.
@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 :)
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[,]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.