TypeOf Function

Purpose

Queries the type of an object

Syntax

If TypeOf(object) Is objecttype

If TypeOf object Is objecttype

object:OLE object
objectname:OLE type name

Description

TypeOf is always part of an If expression, of the form TypeOf objectname Is objecttype. The object is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by objecttype; otherwise it is False.

Example

OpenW 1

Local obj As Object

Ocx Command cmd1

Set obj = cmd1 : result(obj)

Set obj = Win_1  : result(obj)

Set obj = Nothing  : result(obj)

 

Function result(obj As Object)

Try

If TypeOf(obj) Is Command

Print obj.name & " is a Command Button"

Else

Print obj.name & " is not a Command Button. It is a " & TypeName(obj) & "."

EndIf

Catch

Print "The Object is set to Nothing"

EndCatch

EndFunc

Remarks

Select Case may be more useful when evaluating a single expression that has several possible actions. However, the TypeOf objectname Is objecttype clause can't be used with the Select Case statement.

TypeOf can only be used with Objects but, as seen in the example above, does not recognise when the object is set to Nothing and returns an error. Therefore, it should always be contained within a Try/Catch construct if there is even the remotest possibility of the object being queried not having been defined and this is especially true if you are querying the edit box of a ComboBox which returns Nothing eventhough it has been defined. TypeName could be used instead as it recognises both Objects and the Nothing state of undefined objects. This is shown best by the following example:

Type COMBOBOXINFO

- Long cbsize

rcItem As RECT

rcButton As RECT

- Long stateButton, hwndCombo, hwndItem, hwndList

EndType

Type RECT

- Long Left, Top, Right, Bottom

EndType

Global Const CB_GETCOMBOBOXINFO = 0x0164

Ocx ComboBox cb = "", 10, 10, 100, 22

Local a$, ci As COMBOBOXINFO : ci.cbsize = SizeOf(COMBOBOXINFO)

~SendMessage(cb.hWnd, CB_GETCOMBOBOXINFO, 0, V:ci)

Text 10, 50, "ComboBox Edit BoxHandle: " & ci.hwndItem

Try

If TypeOf(cb) Is ComboBox Then a$ = a$ & "TypeOf recognises the ComboBox"

If TypeOf(OCX(ci.hwndItem)) Is TextBox Then a$ = a$ & " and the Edit Box"

Catch

a$ = a$ & " but not the Edit Box as it is not an OCX object and returns Nothing, "

a$ = a$ & "as is shown by TypeName(OCX(ci.hwndItem)) = " & #34 & "Nothing" & #34 & " being returned as" & (TypeName(OCX(ci.hwndItem)) = "Nothing")

EndCatch

Text 10, 65, a$

Do : Sleep : Until Me Is Nothing

See Also

TypeName, VarType

{Created by Sjouke Hamstra; Last updated: 14/09/2015 by James Gaite}