tags:

views:

439

answers:

1

I believe that IDictionary classes works better with sortable objects. I believe also that the IComparer interface is necessary to sort objects from a class. I also read at MSDN that when you implement IComparable you'll need to override the Equals method (and GetHashCode by extension I presume).

I have three doubts:

1) Any of the assumptions above are incorrect?

2) When I implement IComparer I'll have to follow the same IComparable guidelines?

3) When I override the Equals method I'll have to override the == operator, or just the inverse is true?

+5  A: 

(I've left generics off most of this - the same principles hold for the generic and non-generic forms. There isn't a nongeneric IEquatable interface, as System.Object has the relevant methods in already.)

Objects don't have to be sortable to be useful as IDictionary keys. However, they have to have a reasonable hashcode and equality implementation.

Unless you're using a dictionary which actually sorts the keys, you should be more interested in IEqualityComparer and IEquatable - you don't need to be able to say that one object is greater or less than another, just whether or not they're equal and what one object's hash code is (in a manner consistent with Equals).

Implementing IEquatable is like implementing IComparable - it means that an object can compare itself with another object of the specified type (usually the same type). Although you don't have to override Equals(object) in order to implement IEquatable, it would be highly recommended.

Implementing IEqualityComparer is like implementing IComparer - instead of comparing "this" object with another one, the Equals/Compare method takes two values to compare. Implementations of IEqualityComparer/IComparer rarely override object.GetHashCode or object.Equals, unless they want to allow comparisons of comparers - rarely useful.

For your third point: overriding Equals certainly doesn't force you to overload == (you can't override operators, only overload them). You can choose whether or not you want to do this.

Jon Skeet