VB.NET array parameter mechanism, byval and byref

2.4k views Asked by At

As a beginner, my question is if an array is passed byval, what on earth the parameter get? I know that array is kind of reference type. and my guess is that the array parameter byval (hold the array from the argument) should get the copy of the reference of the argument hold, and so, once the sub ArrayProcByRef changed element in the array parameter, the argument should change either.

Sub Main() Handles MyBase.Load
    Dim Array1(10) As Integer
    Dim Array2(10) As Integer

    ArrayProcByRef(Array1, Array2)
    Console.WriteLine(UBound(Array1))
    Console.WriteLine(UBound(Array2))

    Console.WriteLine(Array1(2))
    Console.WriteLine(Array2(2))

End Sub


Sub ArrayProcByRef(ByVal arr1() As Integer, ByRef arr2() As Integer)
    ReDim arr1(100)
    ReDim arr2(100)
    arr1(2) = 11
    arr2(2) = 22
End Sub

above is my code, it is easy, and the output is 10,100,0,22 anyone could give a tip?

1

There are 1 answers

2
jmcilhinney On BEST ANSWER

The point of declaring a reference type parameter ByRef is so that you can assign a different object to that parameter inside the method and have that affect the original variable and that's exactly what is happening in your code. ReDim doesn't change an existing array. It creates a new array of the specified size and assigns it to the same variable. This:

ReDim arr1(100)

is functionally equivalent to this:

arr1 = New Integer(100) {}

So, in your method you create two new arrays and assign them to the parameters. Because the first parameter is declared ByVal, the variable that you pass to that parameter as an argument is unchanged after the method returns, i.e. Array1 still has 11 elements and they all have default values. Because the second parameter is declared ByRef, it is affected by what you do in the method, so it has 101 elements and the third one is what you set inside the method.

Now, if you get rid of the ReDim statements and just leave the assignments, you'll find that both variables are affected by the changes. That's because arrays are reference type objects so the array objects you modify inside the method are the same objects you access outside the method. Modifying an reference type object affects the original variable whether using ByVal or ByRef while assigning a new object to a parameter only affects the original variable when using ByRef.