Linq object equality and how to properly override it?

Sealed class CompareUsersById : IEqualityComparer { public bool Equals(User x, User y) { if(x == null) return y == null; else if(y == null) return false; else return x. ID == y. ID; } public int GetHashCode(User obj) { return obj.ID; } } and then var excludes = users.

Except(matches, new CompareUsersById()).

1: This works. Why did you make this class sealed? – VoodooChild Oct 9 '10 at 20:20 Just a habit - if I'm pretty much sure that class won't be inherited or there is no reason to inherit it, I make it sealed.

– max Oct 9 '10 at 20:22.

Your User class doesn't override Equals and GetHashCode so the default implementation of Equals is used. In this case this means it compares the references. You have created two user objects with the same values, but because these are differenct objects they compare unequal.An alternative to overriding Equals is to use the overload of Except that takes an IEqualityComparer.

– VoodooChild Oct 9 '10 at 20:22 2 Yes, it's exactly this case. Overriding Equals should be considered with caution because this logic will apply anywhere User object is used (but you might actually need this behavior); supplying IEqualityComparer limits comparison rules to just a single call. Btw, I wonder why they did'n make an Except overload which takes a more lightweight Comparison delegate, which eliminates the need to declare a whole new class since a delegate can be anonymous.

– max Oct 9 '10 at 20:30.

For a List, it will check equality merely based on how you have defined Equals method, say for Contains method. For most scenario you will need Equals only. But if you have a HashSet then absence and presence checks will utilize hash of your objects.

Framework indeed asks us to implement good hashing approaches (without re-inventing the wheel) at appropriate places. Any help would be greatly appreciated.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions