Check instance of class is in array

I am looking for an efficient way to check if there is an instance of a class contained within an array.

So something like this:

if classInstance.InArray(classArray) then
//found instance in array
end if

instead of this (which is probably the most efficient way but I am unsure):

for each compare as className in classArray
if  classInstance = compare then
//found instance in array
exit for
end if

Does array.IndexOf work for a class? If so, that will be faster than your loop. Otherwise, your loop is best.

It does - it compares the references

Thanks. I use IndexOf a lot for comparing references so I know that works. I overlooked the use of IndexOf so thanks. I will give this a try.

Would you mind posting the syntax for IndexOf for classes? I was never able to get IndexOf to work with classes, but maybe I’m doing it wrong. It always returns -1.

dim arr() as variant
arr.append( new myClass )

dim a as variant = new myClass
dim b as new myClass
 
dim c as integer
c = arr.indexOf( a ) // compare using variant, c = -1
c = arr.indexOf( b ) // compare using class, c = -1

I’ve used “IsA” in a loop successfully:

if arr( i ) IsA myClass then ...

The way your code is written, it should return -1. You stored an instance of your class, but never look for that particular instance.

Try this:

dim arr() as variant
dim m as new myClass
arr.append m

dim a as variant = new myClass
dim b as new myClass
 
dim c as integer
c = arr.IndexOf( m ) // Will return 0
c = arr.indexOf( a ) // compare using variant, c = -1
c = arr.indexOf( b ) // compare using class, c = -1

Also, if your array is always going to be of the same class, you should declare it as that class rather than a Variant.

dim arr() as myClass

If you are looking for members of an array that belong to a particular class, then you must loop using IsA as you described.

IndexOf tests for the existence of a specific instance of the class, not any instance. Eg.,

dim a as new myClass
dim b as new myClass
dim arr() as myClass

arr.append a

dim c as integer
c = arr.indexof(a)  // c = 0
c = arr.indexof(b)  // c = -1

dim d as myClass
d = a
c = arr.indexof(d) // c = 0
d = b
c = arr.indexof(d) // c = -1

Kem beat me to it.

ooooh. Now I see.

In the project I had worked on, I needed to know only if an array contained an (any) instance of a particular class, but I didn’t care about a specific instance. Now I understand why IndexOf wasn’t working for me.

Thanks for clearing that up for me.