"JB" <jb*****@gmail. com> wrote:
I've created a generic of type List<T> where T is a custom class. I
need to use the List<T>.Contain s method. I know I need to implement
the IEqualityCompar er but I can't seem to get the Contains method to
execute my Equals code. What am I doing wrong?
You don't need to implement IEqualityCompar er. See the code below. NB.
The documentation says that List<T>.Contain s uses
EqualityCompare r.Default, so you providing your own IEqualityCompar er
isn't going to do any good. But read the documentation for
EqualityCompare r.Default. It says it will use System.IEquatab le if T
supports it, but otherwise will fall back on the overrides of
Object.Equals and Object.GetHashC ode. (and I've provided
implementations of these two).
class NameValue
{ public string Text, Value;
public override bool Equals(object obj)
{ NameValue that = obj as NameValue; if (that==null) return false;
return (this.Text==tha t.Text && this.Value==tha t.Value);
}
public override int GetHashCode()
{ return Text.GetHashCod e() ^ Value.GetHashCo de();
}
}
public static void Main(string[] args)
{ List<NameValue> mylist = new List<NameValue> ();
NameValue x = new NameValue(); x.Text="hello"; x.Value="World" ;
mylist.Add(x);
NameValue y = new NameValue(); y.Text="hello"; y.Value="World" ;
bool c = mylist.Contains (y);
}
NB. For your NameValue, I'd be inclined to make it a struct. In which
case you should also provide == and !=, just for sake of good
programming practice. Here:
struct NameValue
{ public string Text, Value;
public override bool Equals(object obj)
{ if (obj==null || obj.GetType()!= this.GetType()) return false;
return this == ((NameValue)obj );
}
public override int GetHashCode()
{ return Text.GetHashCod e() ^ Value.GetHashCo de();
}
public static bool operator != (NameValue x, NameValue y)
{ return !(x==y);
}
public static bool operator == (NameValue x, NameValue y)
{ return (x.Text==y.Text && x.Value==y.Valu e);
}
}