Variable/Object instantiation

In the section on Declarations you saw how variables and objects are declared. This section discusses how objects are instantiated and values assigned to variables/objects.

Assignment

In this discussion, we distinguish between variables that hold values and variables that represent objects. In the first case, a value is assigned; in the second, the object must be instantiated.

By default, the .NET Framework insists that the data type of the value assigned matches the data type with which the variable was declared. Classic VB(A) and VB.NET with Option Strict Off will at runtime attempt to implicitly convert the data type of the value being assigned to that with which the variable was declared. If it the attempted conversion is not successful a “Type mismatch” error will be thrown.

Variables

In all languages, the assignment of a value looks as follows: object designation, followed by an equals sign, then the value.

variable = value

 Objects

 In the .NET languages, the instantiation and assignment for an object looks the same as for a variable. In classic VB(A) the keyword Set is required.

Set object = object

Scope

 By scope we mean how long a variable or object retain the assigned content.

Variables / object declared as part of a procedure go out of scope at the end of the procedure – the information is lost at that point.

Information stored in variables / objects passed to a procedure as a parameter is lost at the end of the procedure if the variable / object was passed by value. If it was passed by reference the information should return to the calling procedure.

Variables and objects can also be declared “outside” of procedures. In .NET, one uses the term “class level variable” as all code is part of a class.

In VBA, where “code modules” are still used, the term “module level” is more appropriate. These variables must be listed before the first procedure.

Variables and objects at the class or module level only lose their content when the application finishes.

Release objects

Under certain circumstances, it is necessary to release the content assigned to objects. Perhaps you want to re-use the object, or you want to free up memory or other resources.

In the VB languages you assign the value Nothing to the object. In classic VB(A) you must precede this with the keyword Set (which is not used in VB.NET):

Set MyObject = Nothing

In C# you assign the object the value null:

object = null;
Leave a Reply