Reputation: 837
I declared an array like
string[] arr1;
string[] arr2;
In one point i assigend value for that
arr1 = new string[] { "value1" , "Value2 };
arr2 = arr1;
After that again i am changing that value of arr1 like
arr1[0]="value3";
arr1[1]="value4";
now if i check the arr2 these changes in arr1 also reflects.
arr2[0] value is "value3";
arr2[1] value is "value4";
how its happening ?
Upvotes: 0
Views: 71
Reputation: 149050
Arrays are reference types in .NET. When you did arr2 = arr1
you made both variables point to the same array in memory. Any change to the elements of one will be directly reflected in the other.
To make a copy of an array, use the Array.Clone
method:
arr2 = (string[])arr1.Clone();
or Linq's Enumerable.ToArray
method:
arr2 = arr1.ToArray();
Upvotes: 6
Reputation: 10171
because arr2
is reference to arr1
so arr2
is point to arr1
in memory. every change to arr1
will reflect to arr2
.
Upvotes: 1