0

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?

gideon
  • 19,329
  • 11
  • 72
  • 113
Dmitry Makovetskiyd
  • 6,942
  • 32
  • 100
  • 160

1 Answers1

3

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.

Community
  • 1
  • 1
Chad La Guardia
  • 5,088
  • 4
  • 24
  • 35
  • why do i want to serialize, to tell you the truth i want it to be a shallow copy, that wont effect my Object array, because every manipulation that i make on the array , influences that array. it simply stored in memory, not like a primitive variable. i need a temp array, to manipulate without manipulating the other array, thats my goal – Dmitry Makovetskiyd Mar 23 '11 at 09:28
  • what do i pass the method as an argument? DeepClone(pieces); this doesnt work – Dmitry Makovetskiyd Mar 23 '11 at 09:42
  • if you want to create a copy of the array and a copy of the references, you can use the `CopyTo()` method to make a different temp array with the same references in it. You can then modify the temp array without modifying the original one. However, if you modify the objects inside the temp array, you will also modify the objects inside the original. – Chad La Guardia Mar 23 '11 at 19:22