Constructing new Random objects during execution

Classes like Button and Label are in the VS.NET toolbox, and we create instances of them at design time. However, many classes are not in the toolbox and have no representation in the user interface. One of those "invisible" classes is Random, which was used in our note on the Random class,

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 declare-then-construct process was accomplished in the first line of our random number program:

Dim rnGenerator As Random = New Random()
The portion to the left of the equal sign creates an object variable that will refer or point to the new object once it is created. The object variable is called rnGenerator.

The right hand side constructs a New instance of the class Random and assigns it to the just created object variable. The class definition is used as a template for the new object. In constructing the new object, the computer sets aside space to hold values for all of the properties of the new object.

The syntax of the constructor call is:

Dim <object variable> As <class name> = New <class name>([<list of arguments>])
The optional argument list is used to initialize the object. In this case no arguments are needed.

When we create objects using the toolbox, we place an icon on a form, and 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 Random objects are created at run time, we use constructor arguments to set the initial values of their properties.

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.