How to check if an object is a collection

I keep getting this error in one of my scripts:

Object not collection

So, I would like to create a function that checks if an 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 feel like I am missing some checks - for sure, only the available types are not just String , Empty or Collection ?

I thought it was better to just try and list param , and if that returns an error, then I know that the output is false - does this seem like the best 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, it would be reasonable to indicate whether this error is: "The object is not a collection"?

+5
source share
1 answer

VBScript does not support type introspection. You can check the TypeName param , but then you need an authoritative list of all classes that implement the enumerated interface.

I would say that your best bet is to enumerate param and check for a 451 error at runtime :

 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 localization of On Error Resume Next as localized as possible, preferably use it only inside this function.


As Tomalak noted in the comments, the above report will present not only β€œnormal” collections in the form of collections, but also built-in VBScript arrays (since they are also enumerated). To avoid this, change the line

 IsCollection = True 

in

 IsCollection = Not IsArray(param) 
+2
source

Source: https://habr.com/ru/post/1244649/


All Articles