Testing the effects of passing array references using ByVal and ByRef : Array Parameters « Collections « VB.Net Tutorial






Module Tester

   Sub Main()
      Dim i As Integer

      Dim firstArray As Integer()
      Dim firstArrayCopy As Integer()

      firstArray = New Integer() {1, 2, 3}
      firstArrayCopy = firstArray

      For i = 0 To firstArray.GetUpperBound(0)
         Console.Write(firstArray(i) & " ")
      Next

      FirstDouble(firstArray)

      For i = 0 To firstArray.GetUpperBound(0)
         Console.Write(firstArray(i) & " ")
      Next

      If firstArray Is firstArrayCopy Then
         Console.WriteLine("The references are equal.")
      Else
         Console.WriteLine("The references are not equal.")
      End If

      Dim secondArray As Integer()
      Dim secondArrayCopy As Integer()

      secondArray = New Integer() {1, 2, 3}
      secondArrayCopy = secondArray

      For i = 0 To secondArray.GetUpperBound(0)
         Console.Write(secondArray(i) & " ")
      Next

      SecondDouble(secondArray)

      For i = 0 To secondArray.GetUpperBound(0)
         Console.Write(secondArray(i) & " ")
      Next

      If secondArray Is secondArrayCopy Then
         Console.WriteLine("The references are equal.")
      Else
         Console.WriteLine("The references are not equal.")
      End If

   End Sub ' Main

   Sub FirstDouble(ByVal array As Integer())
      Dim i As Integer

      For i = 0 To array.GetUpperBound(0)
         array(i) *= 2
      Next

      array = New Integer() {11, 12, 13}
   End Sub 

   Sub SecondDouble(ByRef array As Integer())
      Dim i As Integer

      For i = 0 To array.GetUpperBound(0)
         array(i) *= 2
      Next

      array = New Integer() {11, 12, 13}
   End Sub 

End Module
1 2 3 2 4 6 The references are equal.
1 2 3 11 12 13 The references are not equal.








8.3.Array Parameters
8.3.1.Pass array
8.3.2.Passing arrays and individual array elements to procedures
8.3.3.Testing the effects of passing array references using ByVal and ByRef