Object Variables and Their Binding
In VB .NET, classes and their objects are everywhere. Of course, there are the classes and objects that we create in our own applications. There are also the classes in the .NET Framework Class Library. In addition, many applications take advantage of the objects that are exposed by other applications, such as ActiveX Data Objects (ADO), Microsoft Word, Excel, Access, various scripting applications, and more. The point is that for each object we want to manipulate, we will need to declare a variable of that class type. For instance, if we create a class named CPerson, then in order to instantiate a CPerson object, we must declare a variable:
Dim APerson As CPerson
Similarly, if we decide to use the ADO Recordset object, we will need to declare a variable of type ADO.Recordset:
Dim rs As ADO.Recordset
Even though object variables are declared in the same manner as nonobject variables, there are some significant differences. In particular, the declaration:
Dim obj As MyClass
does not create an object variable—it only
binds a variable name with a class name. To actually construct an
object and set the variable to refer to that object, we need to call
the constructor
of the class. This function,
discussed in detail in Chapter 3, is responsible
for creating objects of the class.
Constructors are called using the New
keyword, as
in:
Dim obj As MyClass = New Myclass( )
or:
Dim obj As MyClass obj = New MyClass( )
VB .NET also provides a shortcut that does not ...
Get VB .NET Language in a Nutshell 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.