CLASS INSTANTIATION DETAILS

When you declare a reference variable, Visual Basic allocates space for the reference. Initially, that reference is set to Nothing, so it doesn’t point to anything and no memory is allocated for an actual object.

You create an object by using the New keyword. Creating an actual object is called instantiating the class.

The following code shows a simple object declaration and instantiation. The first line declares the reference variable. The second line makes the variable point to a new Employee object.

Dim emp As Employee ' Declare a reference to an Employee object.
emp = New Employee  ' Make a new Employee object and make emp point to it.

Visual Basic also enables you to declare and initialize a variable in a single statement. The following code shows how to declare and initialize an object reference in one statement:

Dim emp As Employee = New Employee ' Declare and instantiate an object.

Visual Basic lets you declare a variable to be of a new object type, as shown in the following statement. This version has the same effect as the preceding one but is slightly more compact.

Dim emp As New Employee ' Declare and instantiate an object.

Both of these versions that define and initialize an object in a single statement ensure that the variable is initialized right away. They guarantee that the object is instantiated before you try to use it. If you place these kinds of declarations immediately before the code where the object is used, they also make it easy ...

Get Visual Basic 2012 Programmer's Reference 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.