0

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?

4
  • 4
    The same reference since an array is a reference type. Commented Apr 16, 2013 at 15:31
  • perfect, much appreciated! Commented Apr 16, 2013 at 15:31
  • 1
    The "new int[6];" assigned to array2 will be immediately discarded when array1 is assigned to array2 Commented Apr 16, 2013 at 15:33
  • true, but it's fairly irrelevant for this example anyways. Commented Apr 16, 2013 at 15:34

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.