Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

Problem with array algorithm

I have this method:

public bool CantMoveIfCreatedCheck(Pieces[,] pieces, int rowStart, int columnStart, 
int rowEnd, int columnEnd)

 {
    pieces[rowEnd, columnEnd] = pieces[rowStart, columnStart];
    // shift one piece to another location
        pieces[rowStart, columnStart] = null;

    if (whitePiece)
    {
        for (int z1 = 0; z1 < 9; z1++)
        {  //Find Threatening piece
            for (int j = 0; j < 9; j++)
            {
                if (pieces != null && pieces[whitekingRow, whitekingColumn] != null))// i have some check algorithm
                {
                    canCheck = true;
                    chess.YouWillBeCheckedCantMove();
                }
            }
        }
    }
    pieces[rowStart, columnStart] = pieces[rowEnd, columnEnd];// shift it back to the end location
    pieces[rowEnd, columnEnd] = null;

   return canCheck;   
}

What I am trying to do here, is to change the chess pieces location inside an array momentarily and shift them back just after the two loops finish.

But because everything works with Arrays/objects by reference, a movement of a piece in one location in an array to another location of the array, creates problems. is there a way to somehow change an array to another array, without influencing the original array

For example, creating temperoryArray[,]=pieces[,]; (it didnt work for me, because it copied the references and influenced the pieces array).

Is there an alternative way?

Upvotes: 0

Views: 114

Answers (1)

Chad La Guardia
Chad La Guardia

Reputation: 5164

In order to copy the array to a temp array, you will need to deep copy the objects inside the array instead of shallow copying (simply using assignment) the references. Here's a good SO post about deep copying in C#.

Since you have an array of Objects (really, this is an array of references), assignment simply copies over the reference.

Upvotes: 3

Related Questions