Visual Basic.NET Language Enhancements: Constructors
Author: Intelligent Solutions Inc.
Version Compatibility: Visual Basic.NET
Instructions: Copy the declarations and code below and paste directly into your VB project.
Constructors allow you to create a new instance of a class while simultaneously passing arguments to the new instance. In other words, they allow a new object to be created and initialized in a single expression.
As an example, I am working on a project that has a class called clsTransaction. To be valid, an instance of this class must have a transaction type (such as sale or credit). In VB7, I will be able to write a line such as the following (in the example, TYPE_CREDIT is a value from an enumeration in the class).
Dim oTransaction as clsTransaction Set oTransaction = New clsTransaction(TYPE_CREDIT)
Here, the object is created and initialized in the same line.
What is so good about this? Some objects are simply not valid unless they are initialized with some data. My clsTransaction, for instance, must have a type. By using a constructor, I can ensure that any client code that tries to create an instance of clsTransaction will not compile unless it passes a valid type to the class.
In VB6, there are two workarounds for this type of problem. One is to create a separate method for initialization. For instance, clsTransaction could have a method called SetType, which would take a value from the transaction type enumeration as a parameter. However, this is not adequate, because the class is for other developers, and I cannot force those developers to call the SetType method.
The other workaround is not pretty, but it is what I am forced to do in my current VB6 implementation. In a VB6 DLL, you can set a class's instancing property to PublicNotCreatable. This means that a client program will not be able to create an instance of the class; it instead must call a method of another "parent" class which returns an instance of the "child" PublicNotCreatable class. The method that returns the child class can contain parameters, therefore, this simulates construction in VB6.
For example, my current solution has a class called clsExecutive. This class's instancing property is set to MultiUse. It includes a function called NewTransaction which takes a transaction type as a parameter and returns an instance of clsTransaction, the instancing of which is set to PublicNotCreatable
In VB.NET, construction will simplify my application and others with similar requirements. It will also bring Visual Basic in conformance with other object-oriented languages (e.g., C++, Java) which support construction.
The rest of the series: