Value and Reference Types
Here, we will explore the difference between value and reference types. Since arrays are reference types, it is important for you to understand how reference types work.
Let us show why this notion is so critical with an example:
Try executing this program yourself to see what happens. The problem is
that when we wrote the assignment statement
int[] arrayCopyWrong = arrayA
, we copied the reference to the array,
but not the array itself. We now have two ways of accessing our array,
using arrayA
or arrayCopyWrong
, but still only one array.
To correctly copy the array, we need to do something like the following:
Try executing this program. Can you see the difference?
Array
is actually a class (documented at
https://msdn.microsoft.com/en-us/library/system.array(v=vs.110).aspx),
and as such provides several methods. If you have two arrays, array1
and array2
containing the same type of values and of size at least
x
, you can copy the first x
values of array1
into array2
using
Array.Copy(array1, array2, x);
. Try using this method with the
previous example to create a copy of arrayB
.