O'Reilly logo

Learning Visual Basic .NET by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Passing by Value and by Reference

Visual Basic .NET differentiates between value types and reference types. All the intrinsic types (Integer, Long, etc.), as well as structs (described in Chapter 12) are value types. Classes and interfaces (described in Chapter 8 and Chapter 13, respectively) are reference types.

Passing Arguments by Value

In many of the method calls shown in the previous chapters, the parameters were marked with the keyword ByVal. This indicates that the arguments are passed to the method by value; that is, a copy of the argument is passed to the method. Examine the code in Example 9-3. Try to guess what the output will be before reading further.

Example 9-3. Using the ByVal parameter

Option Strict On Imports System Public Class Tester Public Sub Run( ) ' declare a variable and initialize to 5 Dim theVariable As Integer = 5 ' display its value Console.WriteLine("In Run. theVariable: {0}", _ theVariable) ' call a method and pass in the variable Doubler(theVariable) ' return and display the value again Console.WriteLine("Back in Run. theVariable: {0}", _ theVariable) End Sub Public Sub Doubler(ByVal param As Integer) ' display the value that was passed in Console.WriteLine("In Method1. Received param: {0}", _ param) 'Double the value param *= 2 ' Display the doubled value before returning Console.WriteLine( _ "Updated param. Returning new value: {0}", _ param) End Sub End Class 'Tester Module Module1 Sub Main( ) Dim t As New Tester( ) t.Run( ) End Sub End Module ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required