Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equality for anonymous types [duplicate]

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?

like image 442
DBK Avatar asked May 16 '14 20:05

DBK


1 Answers

== 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.

like image 65
Habib Avatar answered Sep 30 '22 08:09

Habib