Constructing new objects during execution

Before we use a variable in a program, we have to declare it. Similarly, we must declare an object variable and construct a new object before we can use it. This two step process is illustrated in our note on file reading.

In that example, we created a new object, a StreamReader, with the following two lines:

   Dim nameFile As System.IO.StreamReader
   nameFile = New System.IO.StreamReader("a:/friends.txt")
Let's look at each line.

The Dim statement creates an object variable which will refer or point to the new object once it is created. The syntax of the Dim statement is:

Dim <object name> As <class name>
The Dim statement sets aside space to hold the address of the object in memory; however, that is all it does. It does not create the object itself. The new object is created using the New method of the class, as illustrated in the second line.

New is a special method of every class. It is called a constructor because it is used to construct new objects using the class definition as a template. The syntax of a constructor call is:

<object variable> = New <class name>([<list of arguments>])
Note that the New method can take arguments. In the case of the StreamReader, the argument is the path to and name of the file to be opened.

When we create objects using the toolbox, we place an icon on a form or in the component tray window. In either case, the code to create the object variable and call the New method is automatically included in our program by the development system at design time. Since they are created at run time, we cannot set the properties of StreamReaders and other non-toolbox objects at design time.

If you are going to create an object variable and assign a new object to it at the same time, you can use a shorthand syntax which combines the two statements into one. For example, I could have used the single statement:

  Private namefile As StreamReader = New StreamReader("c:/friends.txt")
for the two above. (Note that this is a global variable, belonging to the entire form, no single event handler.

Finally, note that strings are a special case. For the sake of execution efficiency, a string is automatically created when it is declared.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.