Data types fall into two categories: values types and reference types. Examples of value types include the built-in data types like Short, Integer, and Long (System.Int16, System.Int32, and System.Int64). Value types are created on the stack, which is the area of memory that is local to a method. When the location is destroyed, the value type is destroyed—the garbage collector does not manage the stack.
Reference types are defined using classes and created on the heap, which is available for the lifetime of the object. The garbage collector manages this area of memory.
By default, both types are passed by value; a copy of the value is placed on the stack. Therefore, any changes made to a variable are local to the method. Example 3-4 demonstrates this concept.
Imports System Public Class App Private Class Counter Public Sub Increment(ByVal x As Integer) x += 1 End Sub End Class Public Shared Sub Main( ) Dim cc As New Counter( ) Dim x As Integer = 1 cc.Increment(x) Console.WriteLine(x.ToString( )) Console.WriteLine( ) Console.WriteLine("Hit ENTER to continue.") Console.ReadLine( ) End Sub End Class
When Example 3-4 is executed, the output will be 1 because a copy of x was passed to the Counter.Increment method. It is useful to use the ByVal keyword explicitly instead of relying on the default behavior:
Public Sub Increment(ByVal x As Integer)
Replacing ByVal with ByRef causes a reference to be passed instead of ...