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 New TheClass()

At runtime there is no difference between the first example and this one, other than code length.

The preceding code both declares the variable obj as data type TheClass and creates an instance of the class, immediately creating an object that you can use. Another variation on this theme is as follows:

Dim obj As TheClass = New TheClass()

Again, this both declares a variable of data type TheClass and creates an instance of the class. It is up to you how you create these instances, as it is really a matter of style. This third syntax example provides a great deal of flexibility while remaining compact. Though it is a single line of code, it separates the declaration of the variable's data type from the creation of the object.

Such flexibility is very useful when working with inheritance or multiple interfaces. You might declare the variable to be of one type — say, an interface — and instantiate the object based on a class that implements that interface. You will revisit this syntax when interfaces are covered in detail in Chapter 3.

So far, you've been declaring a variable for new objects, but sometimes you simply need to pass an object as a parameter to a method, in which case you can create an instance of the object right in the call to that method:

DoSomething(New TheClass())

This calls the DoSomething method, passing a new instance of TheClass as a parameter. This can be even more complex. Perhaps, instead of needing an object reference, your method needs an Integer. You can provide that Integer value from a method on the object:

Public Class TheClass

Public Function GetValue() As Integer

Return 42 End Function End Class

You can then instantiate the object and call the method all in one shot, thus passing the value returned from the method as a parameter:

DoSomething(New TheClass().GetValue())

Obviously, you need to carefully weigh the readability of such code against its compactness. At some point, having code that is more compact can detract from readability, rather than enhance it.

Was this article helpful?

0 0

Post a comment