The Heap

The heap is an undifferentiated block of memory; an area of RAM in which your objects are created. When you declare an object (e.g., milo) you are actually declaring a reference to an object that will be located on the heap.

A reference is a variable that refers to another object. The reference acts like an alias for the object. When you allocate memory on the heap with the New operator, what you get back is a reference to the new object:

Dim milo As New Dog()

Your new Dog object is on the heap. The reference milo refers to that object. The reference milo acts as an alias for that unnamed object, and you can treat milo as if it were the Dog object.

You can have more than one reference to the same object. This difference between creating value types and reference types is illustrated in Example 18-1. The complete analysis follows the output.

Example 18-1. Heap versus stack

Module Module1 Public Class Dog Public weight As Integer End Class Public Sub Main() ' create an integer Dim firstInt As Integer = 5 ' create a second integer Dim secondInt As Integer = firstInt ' display the two integers Console.WriteLine( _ "firstInt: {0} second Integer: {1}", firstInt, secondInt) ' modify the second integer secondInt = 7 ' display the two integers Console.WriteLine( _ "firstInt: {0} second Integer: {1}", firstInt, secondInt) ' create a dog Dim milo As New Dog() ' assign a value to weight milo.weight = 5 ' create a second reference to the dog Dim fido As Dog = milo ' display their values ...

Get Programming Visual Basic 2005 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.