[Solved] Why changes is one array data changing the value of another array in C# [duplicate]


Why the arr[1] value is changing when changing the value of arr1[1]?

This is your first question, but keep it now after answering the second.

and similarly why it is changing when ((int[])o)[1] = 1000;

This is your second question.
Answer is by seeing what is the initial value of o variable.

Object o = arr;

The previous line sets o to arr, but it’s not copying the elements from arr to o. They’re reference types, so, now both o and arr refers to the same memory block. Therefore, any changes made to arr will affect o and vice-versa. Because they’re sharing the same memory.

Now, let’s get back to your first question:

It’s really the same answer as the second one.

int[] arr1 = (int[])o;

The previous line sets arr1 to o, but again, they just holds the same memory address.

To summarize:

  • You created arr
  • You created o and made its reference the same as arr, so they both share the same memory.
  • You created arr1 and made its reference the same as o which also same as arr. so, arr and arr1 and o, all have the same reference.

Any change to any of them will affect the others.

3

solved Why changes is one array data changing the value of another array in C# [duplicate]