Equality for Anonymous Types

Why is the semantics of Equals () and == different when using anonymous types for comparison? Why are values ​​and other comparison links compared? What is the reason for this?

+6
source share
1 answer

== does not call Equals , it searches for an overloaded == operator. Since anonymous types do not have an overloaded == operator, therefore C # uses a reference comparison for it.

But with Equals it compares field values. This is why the result between == and Equals is different.

Anonymous Types (C # Programming Guide)

Because the Equals and GetHashCode methods for anonymous types are defined in terms of the Equals and GetHashCode methods of a property, two instances of the same anonymous type are equal if all their properties are equal.

+9
source

Source: https://habr.com/ru/post/969403/


All Articles