bababaram
bababaram

Reputation: 35

Storing lots of Arrays into a List on every Loop

I have a question about storing lots of arrays into a list.

First, I initialize the array and list:

int[] arr = new int[9];
List<int[]> forkarr = new List<int[]>();

then I run through a lot of for loops and modify the array each time in order to produce all possible tic tac toe variations. While looping through all those variations, if the array is a possible board then I print it, and additionally if the array meets certain criteria for being a 'fork', then I will add it to the list like this:

if (ForkCheck.fork(arr)) { forkarr.Add(arr); Console.WriteLine("It's a Fork!");}

which also prints that message letting you know that particular array is a fork.

Now, when I am printing all of the arrays, the ones that are forks are printed properly and labeled as such.

However, when I go to print out all of the int[] elements of my list forkarr like so:

foreach (int[] arry in forkarr)
            {
                PrintGame.print(arry);//this is my method that prints the array
                Console.WriteLine();
            }

for some reason each array becomes an identical:

222
222
222

(I'm using 2 as 'X' and 1 as 'O' and 0 as 'empty' btw)

And it just prints that out over and over for all the forks.

So, something is going wrong when I am adding each modification of the array as a new element in the list I think, but I'm not sure why.

Thanks for any help.

Upvotes: 0

Views: 37

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Because you are modifying the same array and adding it to the list. Each time you done with one array array you need to create a new instance like this:

arr = new int[9];

This will create a new reference which will be independent from other arrays. And modifying it's elements wont affect the others.

For more information about value vs reference types you can refer to the question below:

What is the difference between a reference type and value type in c#?

Upvotes: 1

Related Questions