VB.Net/Language Basics/ByRef
Array passed By Reference
<source lang="vbnet"> Imports System Public Class MainClass
Shared Sub Main(ByVal args As String()) Dim i As Integer " declare array references Dim secondArray As Integer() Dim secondArrayCopy As Integer() " allocate secondArray and copy its reference secondArray = New Integer() {1, 2, 3} secondArrayCopy = secondArray Console.WriteLine(vbCrLf & "Test passing array " & _ "reference using ByRef.") Console.Write("Contents of secondArray before " & _ "calling SecondDouble: ") " print contents of secondArray before procedure call For i = 0 To secondArray.GetUpperBound(0) Console.Write(secondArray(i) & " ") Next " pass secondArray using ByRef SecondDouble(secondArray) Console.Write(vbCrLf & "Contents of secondArray " & _ "after calling SecondDouble: ") " print contents of secondArray after procedure call For i = 0 To secondArray.GetUpperBound(0) Console.Write(secondArray(i) & " ") Next " test whether the reference was changed by SecondDouble If secondArray Is secondArrayCopy Then Console.WriteLine(vbCrLf & "The references are " & _ "equal.") Else Console.WriteLine(vbCrLf & "The references are " & _ "not equal.") End If
End Sub " procedure modifies elements of array and assigns " new reference (note ByRef) Shared Sub SecondDouble(ByRef array As Integer()) Dim i As Integer " double contents of array For i = 0 To array.GetUpperBound(0) array(i) *= 2 Next " create new reference, assign it to array array = New Integer() {11, 12, 13} End Sub " SecondDouble
End Class
</source>
Modify Array Element By Reference
<source lang="vbnet"> Imports System Public Class MainClass
Shared Sub Main(ByVal args As String()) Dim array1 As Integer() = New Integer() {1, 2, 3, 4, 5} Dim i As Integer Console.WriteLine( "The values of the original array are:" & vbCrLf ) " display original elements of array1 For i = 0 To array1.GetUpperBound(0) Console.WriteLine( " " & array1(i) ) Next " array element passed by reference ModifyElementByRef(array1(3)) Console.WriteLine( vbCrLf & "array1(3) after " & _ "ModifyElementByRef: " & array1(3) ) End Sub Shared Sub ModifyElementByRef(ByRef element As Integer) Console.WriteLine( vbCrLf & "Value received in " & _ "ModifyElementByRef: " & element ) element *= 2 Console.WriteLine( vbCrLf & "Value calculated in " & _ "ModifyElementByRef: " & element ) End Sub " ModifyElementByRef
End Class
</source>
Pass parameter By value or By Reference
<source lang="vbnet"> Imports System Imports System.Diagnostics Public Class MainClass
Shared Sub DoubleItByVal(ByVal X As Single) X *= 2 End Sub Shared Sub DoubleItByRef(ByRef X As Single) X *= 2 End Sub Shared Sub Main() Dim value As Single value = 10 DoubleItByVal(value) Console.WriteLine(value) value = 10 DoubleItByRef(value) Console.WriteLine(value) End Sub
End Class
</source>