# How to copy a multidimensional array?

I’m trying to make a Astar-pathfinding system and have encountered some bugs, and the first one is that I can’t seem to find a good way to copy a multidimensional array.

I was looking at some examples here on answers but I cant find a good way to do this efficiently.

Here is the code, init runs only once at the start and after that I want to copy the array to grid without modifying the first one.

private Node[,] refGrid;

//initiate the pathfinder.
public void init(int width, int height){

refGrid = new Node[width, height];

for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
refGrid[x,y] = new Node(x, y);
}
}
}

public List<Node> CalculatePath(int startX, int startY, int endX, int endY){

//copy the reference array to grid. (this is where I don't know what to do)
Node[,] grid = new Node[refGrid.GetLength(0), refGrid.GetLength(1)];
System.Array.Copy(grid, refGrid, refGrid.GetLength(0)*refGrid.GetLength(1));

//rest of the code omitted.

}

Can’t you simply:

Node[,] grid = new Node[refGrid.GetLength(0), refGrid.GetLength(1)];
for (int x = 0; x < refGrid.GetLength(0); x++)
for (int y = 0; y < refGrid.GetLength(1); y++)
grid[x, y] = refGrid[x, y];

Don’t know if your Node is struct or class, so above will either store a copy or a reference.

Also, this sounds very inefficient for A* – copying the whole map on each search.