Kyyrbes
Kyyrbes

Reputation: 9

Array memory c# (copied to new reference or using the same?)

So I couldn't seem to figure this out. In the following code:

int[] array1 = { 86, 66, 76, 92, 95, 88 };
int[] array2 = new int[6];
array2 = array1;

When array2 is "copying" the values of array1, is it creating new memory references or is it referencing the same memory index as the values in array1?

Upvotes: 0

Views: 519

Answers (3)

Steve's a D
Steve's a D

Reputation: 3821

Arrays are of reference type. You can easily check this yourself

array2[1] = 2;
Console.WriteLine(array1[1]); // will print out 2

When you change one you change the other because both point to (reference) the same memory location.

Upvotes: 3

treze
treze

Reputation: 3289

It is referencing the same array. So if you change a value in array1 it will also be changed in array2.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460098

Arrays are reference types, therefore you are assigning the same reference.

Array types are reference types derived from the abstract base type Array.

If you want to create a deep copy, you can use Array.Copy:

int[] array1 = { 86, 66, 76, 92, 95, 88 };
int[] array2 = new int[array1.Length];
Array.Copy(array1, array2, array1.Length);

Upvotes: 4

Related Questions