Reputation: 1506
I have this code:
static int[] a = {0 , 10 , 20, 30, 40};
public static void Main()
{
for (int i = 0; i < 10; i++){
int[] array = a;
for (int j = 1; j < array.Length; j++)
array[j] += array[j - 1];
Console.WriteLine(array[4]);
}
}
In the console I get the following result:
100
200
350
560
840
But I did not expect this or it is not what I want. I wanted the following result:
100
100
100
100
100
I have no idea why this is happening. How can I solve this?
Upvotes: 0
Views: 154
Reputation: 101
Your problem is object referance. You can try this.
for (int i = 0; i < 10; i++)
{
int[] array = new int[5];
for (int e = 0; e < array.Length; e++)
{
array[e] = a[e];
}
for (int j = 1; j < array.Length; j++)
array[j] += array[j - 1];
Console.WriteLine(array[4]);
}
Upvotes: 1
Reputation: 424
Use this: int[] array = a.ToArray();
instead of int[] array = a;
An array in c# is a reference type not value type like int, so when you set a into an array, a and array are same object.
Upvotes: 0
Reputation: 470
You can clone the array
static int[] a = { 0, 10, 20, 30, 40 };
public static void Main()
{
for (int i = 0; i < 10; i++)
{
int[] array = (int[])a.Clone();
for (int j = 1; j < array.Length; j++)
array[j] += array[j-1];
Console.WriteLine(array[4]);
}
}
Upvotes: 0
Reputation: 614
It seems that by doing int[] array = a
you're dealing with the reference of a
, so each time you modify array
(in the j
for loop) you're updating the a
array. In the next loop the value of a
will stay with the previously updated value.
Have a look at the Copy method.
Upvotes: 3