Martin Dzhonov
Martin Dzhonov

Reputation: 1081

Save and load initial state of an array (int[,])

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
}

Upvotes: 1

Views: 149

Answers (4)

VoidStar
VoidStar

Reputation: 571

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);

Upvotes: 2

peterszabo
peterszabo

Reputation: 137

Create a shallow copy with Array.Clone()

Upvotes: 1

mtmk
mtmk

Reputation: 6326

first = second

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

Upvotes: 1

astef
astef

Reputation: 9518

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#?

Upvotes: 1

Related Questions