Share via


Visual Basic Concepts

Implementing Methods in Components

When you declare a method, declare all of its arguments as explicit data types whenever possible. Arguments that take object references should be declared as specific class types — for example, As Widget instead of As Object or As Variant.

Strongly typed arguments allow many user errors to be caught by the compiler, rather than occurring only under run-time conditions. The compiler always catches errors, while run-time testing is only as good as the test suite coverage.

This is as true of optional parameters as it is of the method’s fixed parameters. For example, the Spin method of a hypothetical Widget object might allow either direct specification of spin direction and speed, or specification of another Widget object from which angular momentum is to be absorbed:

Public Sub Spin( _
   Optional ByVal SpinDirection As Boolean = True, _
   Optional ByVal Torque As Double = 0, _
   Optional ByVal ReactingWidget As Widget = Nothing)
   ' (Code to ensure that a valid combination of
   '  arguments was supplied.)
   ' (Implementation code.)
End Sub

For More Information   See "Adding Methods to a Class," in "Programming with Objects," in the Visual Basic Programmer’s Guide. The choice of ByVal or ByRef arguments may affect the performance of your component, as discussed in "How Marshaling Affects ActiveX Component Performance," in "Building Code Components."