Answer the question
In order to leave comments, you need to log in
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);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question