Question the variable change on the array, how to prevent this?

liadinon

New member
Joined
Jan 5, 2020
Messages
1
Programming Experience
Beginner
i have variable store in array when i change the value of the variable it change it on the array, how to prevent this?
all the variables are globals
video that show the problem: 2020-01-05 17-01-16.mp4

the code:
C#:
callerPieces = new List<string[]>();
for (int x = 0; x < 8; x++)
{
    for (int y = 0; y < 8; y++)
    {
        try
        {
            if (lastTurnBoard[x, y, 0].Substring(0, 1) == callerColor)
            {
                callerPiecesItem[0] = x.ToString();
                callerPiecesItem[1] = y.ToString();
                callerPiecesItem[2] = lastTurnBoard[x, y, 1];
                callerPiecesItem[3] = lastTurnBoard[x, y, 0];                         

                callerPieces.Add(callerPiecesItem);
            }
        }
        catch { }
    }
}
 
Last edited by a moderator:
The problem is that you are recycling the same instance of callerPiecesItem. Recall that in C#, most objects are reference types rather than value types. So each entry that you add into callerPieces is a reference to that single instance.

For a quick fix, try moving callerPieces = new List<string[]>(); into the body of your if statement so that you always create a new instance.

As a quick aside you don't seem to be following proper object oriented practices. Don't make things stringly-typed. Instead of using a list of strings to hold stuff about caller pieces, use a class. Maybe something like:
C#:
class CallerPiece
{
    public int X { get; set; }
    public int Y { get; set; }
    public CallerPiece PreviousTurnPlayer1 { get; set; }
    public CallerPiece PreviousTurnPlayer2 { get; set; }
}
 
Please post your code in code tags as demonstrated in Skydivers reply. This helps keep the formatting of your code and also helps with readability.

Wouldn't it also be best to have an array of int and therefore not need to convert to string? callerPiecesItem is in the wrong position in your code. Utilising a decent class you could make better use of your code. Of course its a little hard to give you an example since you never gave the relevant code in your opening post. Ah well
 
Back
Top Bottom