Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check if an Object is a Collection

I keep getting this error in one of my scripts:

Object is Not a Collection

So I would like to create a function which checks whether or not the object is a collection before performing any operations on it.

So far I have created this:

Function IsCollection(param)
    If IsEmpty(param) Then
        IsCollection = False
    ElseIf(TypeName(param) = "String") Then
        IsCollection = False
    Else
        IsCollection = True
    End If
End Function 

But I get the feeling I am missing some checks - surely the only available types aren't just String, Empty or Collection?

I thought it could be better to just try and enumerate param and if this returns an error, then I know to output false - does this seem like a better alternative?

Function IsCollection(param)
    For Each p In param
        ' Anything need to go here?
    Next

    If Err > 0 Then
        IsCollection = False
    Else
        IsCollection = True
    End If
End Function 

Even in the second example, would it be wise to specify whether the error given is "Object is not a collection"?

like image 879
Bassie Avatar asked Mar 08 '16 09:03

Bassie


1 Answers

VBScript doesn't really support type introspection. You could check the TypeName of param, but then you'd need an authoritative list of all classes that implement an enumerable interface.

I'd say your best bet is indeed to actually try to enumerate param and check if you get a runtime error 451:

Function IsCollection(param)
    On Error Resume Next
    For Each p In param
        Exit For
    Next
    If Err Then
        If Err.Number = 451 Then
            IsCollection = False
        Else
            WScript.Echo "Unexpected error (0x" & Hex(Err.Number) & "): " & _
                Err.Description
            WScript.Quit 1
        End If
    Else
        IsCollection = True
    End If
End Function

Make sure you leave the scope of On Error Resume Next as localized as possible, preferably use it just inside this function.


As Tomalak mentioned in the comments, the above will report not only "normal" collections as collections, but also VBScript builtin arrays (since they're enumerable as well). To avoid that change the line

IsCollection = True

to

IsCollection = Not IsArray(param)
like image 197
Ansgar Wiechers Avatar answered Oct 28 '22 01:10

Ansgar Wiechers