O'Reilly logo

Professional Visual Basic 2012 and .NET 4.5 Programming by Todd Herman, Gastón Hillar, David McCarter, Rob Windsor, Billy Hollis, Bill Sheldon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required