Why does the semantics of Equals() and == differs when used to compare anonymous types? Why does one compare values and the other compare references? What is the reason behind it?
Asked
Active
Viewed 2,387 times
1 Answers
10
==
doesn't call Equals
, it looks for ==
overloaded operator. Since anonymous types doesn't have overloaded ==
operator, so C# uses reference comparison for it.
But with Equals
it compares field values. That is why the result between ==
and Equals
differ.
Anonymous Types (C# Programming Guide)
Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashCode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

Habib
- 219,104
- 29
- 407
- 436
-
Thanks! Under the hood, the C# compiler implements a sealed class for anonymous types. The reason as to why == compares references makes perfect sense to me. But Equals() comparing values for reference types doesn't make much sense to me. – DBK May 16 '14 at 20:39
-
I though only string was an exception when it came to comparing strings using Equals(). However, in the case of strings, it make sense. – DBK May 16 '14 at 20:41