There is a general expectation within the Framework that certain operations should always produce the same result. The reason is that certain operations (in particular, sorting and searching, which make up a large portion of any application) rely on these different operations producing meaningful and consistent results. In this case, you are breaking a couple of those assumptions:
- If there is a valid operation
==
between a
and b
, it should produce the same result as a.Equals(b)
- Similar, if there is a valid operation
!=
between a
and b
, it should produce the same result as !a.Equals(b)
- If two objects
a
and b
exist, for which a == b
, then a
and b
should produce the same key when stored in a hash table.
The first two, IMO, are obvious; if you are defining what it means for two objects to be equal, you should include all of the ways you can check for two objects to be equal. Note that the compiler doesn't (in general, cannot) enforce that you actually follow those rules. It's not going to perform complex code analysis of the body of your operators to see if they already mimic Equals
because, in the worst case, that could be equivalent to solving the halting problem.
What it can do, however, is check for cases where you most likely are breaking those rules, in particular, you provided custom comparison operators and did not provide a custom Equals
method. The assumption here is that you would not have bothered to provide operators if you did not want them to do something special, in which case, you should have provided custom behavior for all of the methods that need to be in sync.
If you did implement Equals
to be something different from ==
the compiler would not complain; you would have hit the limit of how hard C# is willing to try to prevent you from doing something stupid. It was willing to stop you from accidentally introducing subtle bugs in your code, but it's going to let you purposely do so if that's what you want.
The third assumption has to do with the fact that many internal operations in the Framework use some variant of a hash table. If I have two objects that are, by my definition, "equal", then I should be able to do this:
if (a == b)
{
var tbl = new HashTable();
tbl.Add(a, "Test");
var s = tbl[b];
Debug.Assert(s.Equals("Test"));
}
This is a basic property of hash tables that would cause very strange problems if it were suddenly not true.