View Single Post
Old 09-17-2014, 05:23 AM
naton naton is offline
Join Date: Aug 2004
Posts: 30
Default When is an array a reference and when is it a copy?

Hi there,

I'm slightly confused regarding when an array is a reference (i.e. a pointer) and when it is a copy.

Please read the comments in the code below and help me understand the code's behavior.


    Public Sub Main()
        Dim arr1() As Double = {1, 2, 3}
        Dim myObject As someClass = New someClass(arr1)

        ' The array Arr2() is a copy of array Arr1(). Isn't it?
        Dim arr2() As Double = arr1

        ' 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)

        Dim arr4() As someClass = arr3

        ' Here I don't understand why arr4(4) is a pointer to arr(5)?
        ReDim Preserve arr4(4)
        Dim arr5() As Double = {4, 2, 6, 9}
        arr4(4) = New someClass(arr5)

        arr5(0) = 0.001
    End Sub

    Private Class someClass
        Private mArray() As Double

        Public Sub New(ByVal a() As Double)
            ' Why is it that mArray is a reference of a() and not a copy of a()?
            mArray = a
        End Sub

        Public Property SetGetArray() As Double()
                ' Why is it that the returned array here is a copy and not a reference to mArray()?
                Return mArray
            End Get
            Set(ByVal a() As Double)
                ' Is mArray() a reference or a copy of a()?
                mArray = a
            End Set
        End Property
    End Class

Last edited by naton; 09-17-2014 at 05:34 AM.
Reply With Quote