Pointers in Visual Basic .NET
Imports System
Module Pointers
' We'll show how reference types work in contrast to value types with
' 2 subs: ZeroVal and ZeroRef. ZeroVal has an Integer parameter,
' so arguments will be passed to it by value. ZeroVal will get a copy
' of ival distinct from the one in the calling sub.
Sub ZeroVal(ByVal ival As Integer)
ival = 0
End Sub
' ZeroRef in contrast has a ByRef Integer parameter, meaning
' that it takes a reference to the Integer. The iref variable in the
' sub body then refers to the same memory location as the original variable.
' Assigning a value to iref changes the value at the referenced address.
Sub ZeroRef(ByRef iref As Integer)
iref = 0
End Sub
Sub Main()
Dim i As Integer = 1
Console.WriteLine("initial: " & i)
ZeroVal(i)
Console.WriteLine("zeroval: " & i)
' In VB.NET, we don't need to explicitly pass the address.
' The ByRef keyword in the sub declaration takes care of this.
ZeroRef(i)
Console.WriteLine("zeroref: " & i)
' We can't directly print memory addresses in VB.NET,
' but we can demonstrate object references
Dim obj As New Object()
Console.WriteLine("object reference: " & obj.GetHashCode())
End Sub
End ModuleVisual Basic .NET doesn’t have pointers in the same way as languages like C or Go. Instead, it uses reference types and the ByRef keyword to achieve similar functionality. Here’s how the concepts translate:
Value types (like Integer) are passed by value by default, similar to the
zerovalfunction in the original example.The
ByRefkeyword is used to pass variables by reference, similar to using pointers in the originalzeroptrfunction.VB.NET manages memory automatically, so you don’t directly manipulate memory addresses. Instead, you work with object references.
To run this program:
Save the code in a file with a
.vbextension, for examplePointers.vb.Compile the code using the VB.NET compiler:
vbc Pointers.vbRun the compiled executable:
Pointers.exe
The output will be similar to:
initial: 1
zeroval: 1
zeroref: 0
object reference: 58225482Note that ZeroVal doesn’t change the i in Main, but ZeroRef does because it has a reference to the original variable. The last line demonstrates how we can print a unique identifier for an object, which is conceptually similar to a memory address in languages with explicit pointer support.