Using TypeOf to test interfaces
In VB 5.0 and VB 6.0, the new Implements keyword allows you to create objects with multiple interfaces. Sometimes, you might need to test if an object being passed to you really implements the interface you think it does.
Related items
The solution to this simple problem is TypeOf. Generally used to test if an object has a certain type (read: class), TypeOf will return correct results if used to test against interfaces. To try this code, create a class called CoolClass. Give it any number of properties and methods you like. Function IsCoolObject(o As Object) As Boolean IsCoolObject = (TypeOf o Is CoolClass) End Sub Sub Main() Dim a As New CoolClass Dim b As New Collection If IsCoolObject(a) Then MsgBox "a is Cool" If IsCoolObject(b) Then MsgBox "b is Cool" End SubAs you will see, only a is cool. If you create a second class CoolClass2 that Implements CoolClass, you would be able to do this: Function IsCoolObject(o As Object) As Boolean IsCoolObject = (TypeOf o Is CoolClass) End Sub Sub Main() Dim a As New CoolClass2 Dim b As New Collection If IsCoolObject(a) Then MsgBox "a is Cool" If IsCoolObject(b) Then MsgBox "b is Cool" End SubAs you will see, a is still Cool, because a implements CoolClass. |
||
Editor: Jens G. Balchen Last update: 2025-01-02 Copyright 1995-2025 VBI |