Working with Objects

In the .NET environment in general and within Visual Basic in particular, you use objects all the time without even thinking about it. As noted earlier, every variable, every control on a form—in fact, every form—inherits from System.Object. When you open a file or interact with a database, you are using objects to do that work.

Objects Declaration and Instantiation

Objects are created using the New keyword, indicating that you want a new instance of a particular class. There are numerous variations on how or where you can use the New keyword in your code. Each one provides different advantages in terms of code readability or flexibility.

The most obvious way to create an object is to declare an object variable and then create an instance of the object:

Dim obj As TheClass
obj = New TheClass()

The result of this code is that you have a new instance of TheClass ready for use. To interact with this new object, you use the obj variable that you declared. The obj variable contains a reference to the object, a concept explored later.

You can shorten the preceding code by combining the declaration of the variable with the creation of the instance, as illustrated here:

Dim obj As TheClass = New TheClass()
Dim obj As New TheClass()
Dim obj = New TheClass()
Note
At run time there is no difference between the first example and this one, other than code length.

The preceding code shows three ways to both declare the variable obj as data type TheClass and create ...

Get Professional Visual Basic 2012 and .NET 4.5 Programming 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.