vb.netparamarray

Confusing ParamArray behavior - are repeated arrays somehow linked?


Sorry if the title and question are not clear; I don't have a good way to describe it. But here it goes:

So what is happening is that "testMat"s are somehow linked together, and it makes the values change even though I'm not redefining them. E.g., if you run this code below, you'll see that in testResult's matSum function the values of out1 and out2 are changing as out changes (in the loop), which I have no idea why! Their values don't change in testResult1's. Where does this behavior comes from?

Sub Main()

    Dim testMat As Double(,) = {{1, 2}, {3, 4}}

    Dim testResult As Double(,) = matSum(testMat, testMat, testMat)
    Dim testResult1 As Double(,) = matSum({{1, 2}, {3, 4}}, {{1, 2}, {3, 4}}, {{1, 2}, {3, 4}})

End Sub


Function matSum(ByVal ParamArray args As Double()(,)) As Double(,)
    'This function sums matrices. It assumes you know how to sum matrices.

    Dim m, n As Integer
    Dim out, out1, out2 As Double(,)
    Dim numArgs As Integer = args.Length

    out = args(0)
    out1 = args(1)
    out2 = args(2)
    m = out.GetUpperBound(0)
    n = out.GetUpperBound(1)

    For v As Integer = 1 To numArgs - 1
        For i As Integer = 0 To m
            For j As Integer = 0 To n
                out(i, j) = out(i, j) + args(v)(i, j)
            Next
        Next
    Next

    Return out

End Function

Solution

  • OK, to get it a little bit more context.

    Array is a reference type, so when it's passed ByVal the value that is being passed is the reference. The array is not copied or cloned. The reference is. But it still points to the same array in memory.

    Now, when you call your method here.

    Dim testResult As Double(,) = matSum(testMat, testMat, testMat)
    

    out, out1 and out2 have the same value - reference to testMat. Modifying values within that array using any of these variables will modify the same array, and you'll see it from other references as well.