Take the 2-minute tour ×

In this question. we discovered that in .NET 1.1, Array.IndexOf(array, value) searched for an element with

value.Equals(arrayElement) == true

while .NET 2.0 changed it to search for an element with

arrayElement.Equals(value) == true

Obviously the potential difference between the two results arises from polymorphism, but is there any reason why the latter version is preferable? More generally, if I have two objects a and b to compare, is there any good reason to prefer a.Equals(b) or b.Equals(a)?

share|improve this question
== true is my bane. –  recursive Aug 28 '09 at 14:20
While I agree with you @recursive, in this context it emphasizes the point of the code snippet. –  Austin Salonen Aug 28 '09 at 14:23
I wouldn't write if ( value.Equals(arrayElement) == true ), but as Austin says, the emphasis seemed useful in this case. –  stevemegson Aug 28 '09 at 14:26
add comment

2 Answers

up vote 2 down vote accepted

I guess this is done to avoid problems when you override Equals in object you're feeding into IndexOf. In other words, if you have class Foo with some weird Equals implementation, this:

Foo f = new Foo();
Bar b = arrayOfDateTimes.IndexOf(f);

could potentially disrupt the behavior and yield strange results.

share|improve this answer
But isn't it just as likely that you've got a weird Equals override on the object stored in the array? They seem to be equally risky, but since it's potentially a breaking change it feels like MS should have had a reason to bother changing. –  stevemegson Aug 28 '09 at 14:45
add comment

Just a guess, but the 1.1 version may have had a higher rate of NullReferenceExceptions compared to the 2.0 version.

share|improve this answer
add comment

Your Answer


