MATLAB COM Builder | ![]() ![]() |
Visual Basic New Operator
This method uses the Visual Basic New
operator on a variable explicitly dimensioned as the class to be created. Before using this method, you must reference the type library containing the class in the current VB project. Do this by selecting the Project menu from the Visual Basic editor, and then selecting References... to display the Available References list. From this list select the necessary type library.
The following example illustrates using the New
operator to create a class instance. It assumes that you have selected mycomponent 1.0 Type Library from the Available References list before calling this function.
Function foo(x1 As Variant, x2 As Variant) As Variant Dim aClass As mycomponent.myclass On Error Goto Handle_Error Set aClass = New mycomponent.myclass ' (call some methods on aClass) Exit Function Handle_Error: foo = Err.Description End Function
In this example, the class instance could be dimensioned as simply myclass
. The full declaration in the form <component-name>.<class-name>
guards against name collisions that could occur if other libraries in the current project contain types named myclass
.
Both methods are equivalent in functionality. The first method does not require a reference to the type library in the VB project, while the second results in faster code execution. The second method has the added advantage of enabling the Auto-List-Members and Auto-Quick-Info capabilities of the VB editor to work with your classes.
In the previous two examples, the class instance used to make the method call was a local variable of the procedure. This creates and destroys a new class instance for each call. An alternative approach is to declare one single module-scoped class instance that is reused by all function calls, as in the initialization code of the previous example.
The next example illustrates this technique with the second method:
Dim aClass As mycomponent.myclass Function foo(x1 As Variant, x2 As Variant) As Variant On Error Goto Handle_Error If aClass Is Nothing Then Set aClass = New mycomponent.myclass End If ' (call some methods on aClass) Exit Function Handle_Error: foo = Err.Description End Function
![]() | Creating an Instance of a Class | Calling the Methods of a Class Instance | ![]() |