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?
==
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With