Question about "Contains" method

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I've built a complex collection object from
"System.Collections.CollectionBase". With regard to it, I have a question
about the "Contains" method.

At first I thought that "Contains" would actually search the entire
collection to tell me whether an object in the collection were identical with
the comparison object I was passing it. But I opened up the same collection
data into two separate collections (loaded them from disk) and did this:

Debug.WriteLine(obj1.Contains(obj2[0]).ToString());

and it returned 'False". Now I *KNOW* that the first elements of both
objects are absolutely identical but the Contains method doesn't seem to
agree.

So I'm wondering what are the limitations of "Contains" when it comes to
collections.
 
ArrayList.Contains uses the Equals method of the collection items to
determine whether they are equal. What is the type of your collection items
and how is Equals implemented for that type?

Kent
 
Hello,
'Contains' method internally uses Equals method to compare the
contained objects.

According to MSDN: The default implementation of Equals supports
reference equality only. For reference types, equality is defined as
object equality; that is, whether the references refer to the same
object. For value types, equality is defined as bitwise equality.

So in short, You will not get 'true' from Contains method, if you are
trying to compare the reference-type objects having same values but
difference references

If you are comparing value-types and not getting true while you know
that the value exists in both list... its a mystery :)

HTH. Cheers.
Maqsood Ahmed - MCAD.net
Kolachi Advanced Technologies
http://www.kolachi.net
 
Thanks, gentlemen. My implementation of CollectionBase was borrowed from an
article I read in my early days of learning C#. It does not explicitly
implement Equals.

Magsood's comment about comparing references only (for a complex object)
makes sense. I guess I'll have to write my own, more complex, comparison
method.

Thank you again!
 
Hi,

It's the contained type the one who needs to override Equals.

cheers,
 
Back
Top