A
A
Alexey Smirnov2017-10-20 21:52:19
.NET
Alexey Smirnov, 2017-10-20 21:52:19

How can I store an array with the same name but different values ​​in a List multiple times?

Hello.
I am trying to write a one dimensional array to a List multiple times.

List<object[]> arrList = new List<object[]>();
object[] anyArr = new object[5];

for (int i = 0; i < 6; i++)
{
    anyArr - каждую итерацию цикла for содержание одномерного массива меняется. 

    arrList.Add(anyArr);
}

At the same time, each time I change the content of the one-dimensional array anyArr.
The problem is that I end up with a List containing 6 (because the for loop counts up to 6) times the array that was in the last iteration of the for loop.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2017-10-20
@ERAFY

Of course, you will have the same array, because you created it once outside the loop.
In C#, an array is a reference type. This means that your anyArr variable stores as its value a reference (!) to an array. If you copy the value of the variable, which is what you are essentially doing in the line arrList.Add(anyArr); you will copy that very reference to the array, but not the array itself (as a result, the reference to the same array will be placed in the list 6 times).
If you want to have 6 different arrays - create them in a loop, or copy the original, depending on what you need to do. Either way, you need 6 different objects of type object[] .
Then read about value types and reference types in C#.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question