0

I want to stack matrices in a list. At first, I add copies of some matrix to the list. Later I calculate a different matrix (without adding it to the list). After this calculation all my list values changed to the new matrix.

Here is the critical snippet of the code.

public class Algorithm
{
    private List<int[,]> mstack = new List<int[,]>();
    private List<int> stack = new List<int>();
    private List<int> solution = new List<int>();
    private bool solfound = false;
    private int col;

    public List<int> X(int[,] Matrix)
    {
        while (!solfound)
        {
            col = HelpMethods.LeastOneColoumn(Matrix);
            List<int> rowone = HelpMethods.OnesInRow(Matrix, col);

            for (int j = 0; j < rowone.Count; j++)
            {
                mstack.Add(Matrix);
            }

            SubMethod(Matrix, solution);
        }

        return solution;
    }

    private void SubMethod(int[,] Matrix, List<int> solution)
    {
        int row = stack[stack.Count - 1];
        int[,] UpdateMatrix = HelpMethods.UpdateMatrix(Matrix, row);//CRITICAL
    }
}

By debugging I found that the last line of the above code changes the values of the list. I'm fairly new to C# and can't find neither the origin of the problem nor a solution to the problem.

Any help is very welcome (also concerning other potential problems with the code). Thanks in advance.

EDIT: By reading the first comments the problem is clear. I still struggle to find a suitable way to implement the following: I want to keep track of the matrices by storing them in order such that I can go back to a previous matrix if necessary and continuously add and delete stored matrices. All my approaches failed. How can I construct such a "memory" without running into the above problem?

sqlman
  • 1
  • 2
  • 2
    "At first, I add copies of some matrix to the list" - no you don't. You add multiple references to the *same* matrix object. There's only one `int[,]` object created in the code you've shown. See https://stackoverflow.com/a/32010236/22656 – Jon Skeet May 02 '20 at 12:15
  • in c# , lists and multidimensional lists (matrix ) by defult only give you a new referecence to old object if you assign to new object , so you need to copy (for lists you can use .CopyTo() method) – emaditaj May 02 '20 at 12:23
  • Thanks for the comments. I edited my question, since I'm struggling to find a solution to the issue. – sqlman May 02 '20 at 17:28
  • Change your code to do what you said you did, make copies of the matrix and add them to the list. – Lasse V. Karlsen May 02 '20 at 17:38

0 Answers0