If I have an object of type MyBull
and a List<MyBull> orig
:
// Just an example
MyBull x = getMeTheObjectWithIdFromDB(9);
orig.add(x);
// Again same? data object
MyBull y = getMeTheObjectWithIdFromDB(9);
Why is this false then?
// This is false, even though all the properties
// of x and y are the same.
orig.Contains<MyBull>(y);
By default objects will expose reference based equality. If you want custom rules, such as equality based on id fields, you need to override the
Equals
andGetHashCode
methods.Does your MyBull object implement
IEquatable<T>.Equals
? This method will determine the equality of two objectsrequested by OP
Your MyBull class would implement IEquatable
and then you would need to override the
Equals
methodAs David Neale mentions below, this is best used when you're comparing objects of the same type--which you are. Overriding Object.Equals and Object.GetHashCode will work too.
This is because the MyBull instances are being compared by reference. From the point of view from .NET, x and y are both different instances and therefore not Equal.
In order to get around this you will have to override the Equals and GetHashCode methods (which means you should probably implement
IEquatable<MyBull>
and override the == and != operators too).If you can use LINQ then you can
...