Problem with ListViewItemCollection 'Contains' method

P

Piotr Szukalski

Hi!

I have trouble with 'Contains' method in ListViewItemCollection class - it
seems like it nevers calls 'Equals' method of class inherited from
ListViewItem... I've found that ListViewItem doesn't override 'Equals'
method, but I _DO_ override it in my class. Have a look at thread:
http://groups.google.com/group/micr...contains+equals&rnum=2&hl=pl#75351591db8d07c5

.... and at this piece of code:

using System;
using System.Collections;
using System.Windows.Forms;

namespace CollectionsTest
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
ArrayList ar = new ArrayList();
ar.Add(new MyClass("1"));
ar.Add(new MyClass("2"));

ListView.ListViewItemCollection col = new ListView.ListViewItemCollection(new ListView());
col.Add(new MyClass("1"));
col.Add(new MyClass("2"));

System.Console.WriteLine("Contains: {0}", ar.Contains(new MyClass("1")));
System.Console.WriteLine("Contains: {0}", col.Contains(new MyClass("1")));
System.Console.ReadLine();
}
}

class MyClass : System.Windows.Forms.ListViewItem
{
private string str;

public MyClass(string s)
{
str = s;
}

public override bool Equals(object obj)
{
return str.Equals(obj.ToString());
}

public override int GetHashCode()
{
return str.GetHashCode ();
}

public override string ToString()
{
return str;
}
}
}

ArrayList do calls my 'Equals' method, but ListViewItemsCollection don't.
Any ideas?

Cheers,
Piotrek
 
G

Guest

ListViewItemCollection.Contains does the equivalent of calling
Object.ReferenceEquals when comparing an item to the items in the list, so it
does not call Object.Equals. This means that ListViewItemCollection.Contains
only compares references. You will have to implement your own comparison if
you consider two items with the same data to be equivalent.

HTH, Jakob.
 
P

Piotr Szukalski

Hi!
ListViewItemCollection.Contains does the equivalent of calling
Object.ReferenceEquals when comparing an item to the items in the list, so it
does not call Object.Equals. This means that ListViewItemCollection.Contains
only compares references. You will have to implement your own comparison if
you consider two items with the same data to be equivalent.

Thanks for your answer. I still consider it strange that one
implementation of IList works one way and another seems to follow other
rules... Well, I'm not M$ to make the law... However I wish to find such
information in docs, because it took a while to find bug in my code.

Many thanks,
Piotrek
 

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