ValueType.Equals is incorrect - by Xiang Fan

Status : 

  Won't Fix<br /><br />
		Due to several factors the product team decided to focus its efforts on other items.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 374654 Comments
Status Closed Workarounds
Type Bug Repros 0
Opened 10/10/2008 5:55:20 AM
Access Restriction Public


ValueType.Equals will return wrong result for structures with members which have overridded Equals function.
That is because the default Equals will do memcmp for these structures as an optimization which is incorrect.
Sign in to post a comment.
Posted by Microsoft on 5/19/2009 at 5:33 PM
It has been decided to resolve this issue as won't fix due to the danger of breaking existing code which depends on the existing logic.

David Wrighton
.NET Framework CLR
Posted by David A Nelson on 10/13/2008 at 8:35 AM
It is true that adding new members with equal values should not change the equality comparison of the type. That is an inconsistency that should probably be corrected. However, I think what this is really demonstrating is that the default Equals comparison for value types is a convenience which should not be relied upon. Equals needs to be overridden so that members can be compared correctly; having the compiler do this for us would be an added bonus.
Posted by Pavel Minaev [MSFT] on 10/11/2008 at 9:38 AM
Not "exactly" - this one is actually a classic overoptimization bug. Note how the _exact same_ float comparison gives different results depending on other members of the struct (which are also equal, and shouldn't affect comparison in any way).

It reminds me a lot of this one:

which is a similar case where someone had mistakenly decided that memcmp should be good for all basic types, forgetting about floating-point NaNs.

Anyway, I don't quite understand why they cannot just make it so that, if you don't override Equals for your struct, the compiler just inserts its own optimal version, that does exactly what ValueType.Equals() does today, but, you know, without all the reflection overhead. It seems to be trivial, and I don't see how it would be a breaking change, either.

BTW, F# does just that for all its structural types.
Posted by David A Nelson on 10/10/2008 at 8:48 AM
This is exactly why it is recommended that you always override the Equals method when defining a value type.