devxlogo

Better type checking in Variant properties that can accept objects

Better type checking in Variant properties that can accept objects

As explained in the Mistake Bank you need all three flavors of Property procedures to correctly implement a Variant property that can take either an object or a non-object value. Surprisingly enough, in this case you don’t need that the argument of the Property Set procedure be declared As Variant. In fact, you can slightly optimize your code by declaring the argument of the Property Set procedure using As Object instead:

Property Set Tag(newValue As Object)    Set m_Tag = newValueEnd Property

You can build on this undocumented capability to write more concise code and further optimize the procedure by using a more specific type of object. For example, let’s assume that the Address property can take either a string or a CAddress object. You might believe that you need to test the type of the object at run-time using this code:

Dim m_Address As VariantProperty Set Address(newValue As Variant)    If TypeName(newValue) <> "CAddress" Then        Err.Raise 1003, , "A CAddress object is expected"    End If    Set m_Address = newValueEnd Property

However, you can let Visual Basic do the test on your behalf, and build a better routine as follows:

Dim m_Address As VariantProperty Set Address(newValue As CAddress)    Set m_Address = newValueEnd Property

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist