View Single Post
 
Old 09-17-2014, 06:13 AM
PlausiblyDamp's Avatar
PlausiblyDamp PlausiblyDamp is offline
Ultimate Contributor

Forum Leader
* Expert *
 
Join Date: Nov 2003
Location: Newport, Wales
Posts: 2,058
Default

Quote:
' The array Arr2() is a copy of array Arr1(). Isn't it?
Dim arr2() As Double = arr1
Nope, arr2 and arr1 are simply references to the same in memory data structure - if you change an item in arr1 then you will see the change reflected in arr2

Quote:
' I don't understand why below arr4() is a copy of aray arr3().
' I thought that arr4 is a pointer to arr3?
Dim arr3(3) As someClass

For i As Integer = 0 To 3
arr3(i) = New someClass(arr1)
Next
In this case you are declaring an array of someClass and then creating four instances of this type and passing arr1 into all of them - again though everything is pointing to the same memory structure, if you change arr1, arr2 or the array contained by any of the items in arr3 you will see all of them change.

Quote:
Dim arr4() As someClass = arr3
The variable arr4 is just a pointer to arr3 - again if you edit any of the items you will see it reflected in all of the items.

The simple rule is that types under .Net are either a ValueType (Structure) or a ReferenceType (Class), if it is a reference type then all direct assignments are done as references. This can be seen in all of the assignments in your code, if you need a copy then you need to take deliberate action (such as an implementation of ICloneable or using Linq's .ToArray etc)

When you look at the final bit of your code
Quote:
ReDim Preserve arr4(4)
Dim arr5() As Double = {4, 2, 6, 9}
arr4(4) = New someClass(arr5)

arr5(0) = 0.001
the reason it is a reference is the fact you are dealing with reference types, this isn't any different to the rest of the posted code. Try stepping through the code in a debugger and change the various references to the array and you will see this is consistent behaviour.

Also if you look at the code in someClass and again use it under a debugger you will see that all the occasions you are using mArray are references, if you assign the result of SetGetArray to a variable and then change one of the values you will again see this reflected in all variables that are referencing the original array.

TL;DR answer - it is always a reference unless you deliberately make a copy.
__________________
Intellectuals solve problems; geniuses prevent them.
-- Albert Einstein

Posting Guidelines Forum Rules Use the code tags

Last edited by PlausiblyDamp; 09-17-2014 at 06:19 AM.
Reply With Quote