1

I'm trying to save the state of an array so I can load it later in it's initial state. But I don't know how to make them separate instances, and not to reference each other. Here's some sample code:

static void Main(string[] args)
{
    int[,] first = new int[5, 5];
    int[,] second = first;

    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 5; j++)
        {
            first[i, j] = i * j;
        }
    }

    first[0, 0] = 10000;
    first = second;
    Console.WriteLine(first[0, 0]); //10000
}
Abbas
  • 14,186
  • 6
  • 41
  • 72
Martin Dzhonov
  • 1,021
  • 4
  • 15
  • 28

4 Answers4

2
int[,] second = first;

Means that the second array is a reference to first, they are the same object. You need to create a new array instance. You mention that you want to save the state of the array for later use and for this, you have to copy your original array like so:

int[,] first = new int[5, 5];
int[,] second = new int[5, 5];
Array.Copy(first, second, first.Length);
VoidStar
  • 581
  • 3
  • 6
1

If you want a separate instance, you need to instantiate it:

int[,] second = new int[5, 5];

Many ways of copying an array can be found here: Any faster way of copying arrays in C#?

Community
  • 1
  • 1
astef
  • 8,575
  • 4
  • 56
  • 95
1
first = second

Only copies the reference. You need to copy the elements one by one, just like the way you populate the first array.

mtmk
  • 6,176
  • 27
  • 32
1

Create a shallow copy with Array.Clone()

peterszabo
  • 137
  • 1
  • 7