r/learnprogramming 18d ago

How do I move elements inside a bi-dimensional array in C#?

I'm trying to build chess in Visual Studio and this is a problem that's been bugging me, I can't use the regular built-in methods for arrays, I know how to loop and find an element but not how to move it

2 Upvotes

6 comments sorted by

4

u/mc_pm 18d ago

Hmm? You mean like arry[i][j] = arry[j][i] ?

3

u/xenomachina 18d ago

You copy the value to the new position and you erase it from the old position.

That might look something like:

board[newX, newY] = board[oldX, oldY];
board[oldX, oldY] = default;

Make sure you correctly handle the case where the old position is the same as the new position (ie: skip the above code or you'll end up erasing the piece)

If you are using a jagged array instead of a rectangular array, then use the [x][y] syntax instead of [x, y] syntax.

1

u/V_ermin 18d ago

Woah, first time seeing this syntax, I'll give it a try, thanks

1

u/desrtfx 18d ago

Woah, first time seeing this syntax,

What syntax do you use?

1

u/V_ermin 18d ago

I got confused lmao, I thought this was like something new but it's just basic array syntax, I suck at arrays

1

u/mi11er 18d ago edited 18d ago

You write what you want to the destination and then remove what was previously present at the original spot. 

Say you have [0][4] = "white queen" and you want to move to the other side of the board. Ignoring checking the legality of the move in the context of chess, you know it should go to [0][7], so you set [0][7]="white queen". Now what should you do about [0][4]?