Here is an example (note that it should also overrde GetHashCode, but can
run without doing that, but couldn't be used reliably with Hashtable unless
implementing that method)
Here is MyObject class which by overriding Equals makes difference between
its instances by comparing id field
===============
public class MyObject
{
//id member to represent identified for the object
private int _id;
public MyObject(int id)
{
this._id = id;
}
public override bool Equals(object obj)
{
//Test if passed object is of same type
MyObject o = obj as MyObject;
if(o != null)
{
//it is, detect if they are same object based on id member data;
return o._id == this._id;
}
return false;
}
}
==========
And here is a usage example with ArrayList comparing with Contains as in
your code
==========
//Create MyObject with ID 1
MyObject obj1=new MyObject(1);
//Create MyObject with ID 2
MyObject obj2=new MyObject(2);
//Create duplicate MyObject with ID 1
MyObject duplicateObj1=new MyObject(1);
ArrayList arrList=new ArrayList();
if(!arrList.Contains(obj1)) {
//THis will be called
arrList.Add(obj1);
}
if(!arrList.Contains(obj2)) {
//THis will be called
arrList.Add(obj2);
}
if(!arrList.Contains(duplicateObj1)){
//This WON'T BE CALLED, because collection already has
//MyOBject with id 1
arrList.Add(duplicateObj1);
}
--
Teemu Keiski
ASP.NET MVP, AspInsider
Finland, EU
"Neven Klofutar" <neven.klofutar*r.e..mo*****@vip.hr> wrote in message
news:eE**************@TK2MSFTNGP14.phx.gbl...
Nope ...
Can you tell me what must I do ... or send a useful link ?
thanx, Neven
"Teemu Keiski" <jo****@aspalliance.com> wrote in message
news:Oj**************@TK2MSFTNGP10.phx.gbl... Have you overridden Equals method in your MyObject class to tell how it
can detect to instances of MyObject from each other?
--
Teemu Keiski
ASP.NET MVP, AspInsider
Finland, EU
"Neven Klofutar" <neven.klofutar*r.e..mo*****@vip.hr> wrote in message
news:Ol*************@TK2MSFTNGP12.phx.gbl... > Hi,
>
> I'm trying to use Contains method, but I have some problems ...
>
>
> // create SqlDataReader
> SqlDataReader dr = ....
>
> // create collection of myObjects
> MyCollection myObjectsColl = new MyCollection();
>
> while (dr.Read()) {
>
> // Creating myObject
> // Sometimes I create myObject using identical values of dr["a"] and
> dr["b"]
> // aren't those object equivalent ?
> MyObject myObject = Getsomething(dr["a"].ToString(),
> dr["b"].ToString());
>
> // trying to add myObject, if it's not present already in myCollection > if (!myObjectColl.Contains(myObject)) {
> myObjectsColl.Add(myObject);
> }
>
> }
>
>
> I don't know why, but (!myObjectColl.Contains(myObject)) is NEVER false
> ...
>
> please help, Neven
>
>