ICollection(Of T) interface - Contains() method

M

Mike

Hi. I have the class below that implements the ICollection(Of Object). My
problem is that I can't seem to build an efficient Contains() method. My
Contins() method logic requires an exception in order to identify that an
item doesn't exist. Is there a better way to program this so I don't have to
catch an exception? Thanks.

Public MustInherit Class AbstractCol
Implements ICollection(Of Object)

Protected _Collection as Collection
Public Function Contains(ByVal item as Object) Boolean Implements
System.Collection.Generic.ICollection(Of Object).Contains
Try
If Not _Col.Items(item) Is Nothing Then Return True
' you would think the above Is Nothing check would prevent an
exception but it doesn't
Catch
' This happens if the item doesn't exist.
Return False
End Try
End Sub
End Class
 
C

Cor Ligthert[MVP]

Mike,

Most of us are very practical (probably that is why we like VB).

Therefore, what is the goal you want to reach, or is this more meant as a
theoretical question?

Cor
 
M

Mike

The goal is write efficient code for the Contains() method, which doesn't
rely on an exception to identify a particular return value. As shown below,
the code relies on an exception to return FALSE. To me this method is
inefficient, so I'm asking if anyone can suggest an alternative.

Thank you
 
C

Chris Dunaway

The goal is write efficient code for the Contains() method, which doesn't
rely on an exception to identify a particular return value. As shown below,
the code relies on an exception to return FALSE. To me this method is
inefficient, so I'm asking if anyone can suggest an alternative.

Thank you

How do you envision using this class? It seems, by implementing
ICollection(Of Object) that you are defeating the purpose of a generic
class. You might as well just implement the non-generic ICollection
interface.

In any event, perhaps using a for loop in the Contains method:

Dim result As Boolean = False
For Each o As Object in _col.Items
If o Is item Then
result = True
Exit For
End If
Next
Return result
 
S

Steve Gerrard

Mike said:
The goal is write efficient code for the Contains() method, which
doesn't rely on an exception to identify a particular return value.
As shown below, the code relies on an exception to return FALSE. To
me this method is inefficient, so I'm asking if anyone can suggest an
alternative.

I would just use one of the several specialized forms of Collection available,
instead of the fairly generic Collection.

Instead of
Protected _Collection as Collection

you could do
Protected _Collection as System.Collections.Specialized.HybridDictionary

or any of several choices which have a Contains method in them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top