Why does the Equals implementation for anonymous types compare fields?

Anonymous type instances are immutable data values without behavior or identity. It doesn’t make much sense to reference-compare them. In that context I think it is entirely reasonable to generate structural equality comparisons for them.

If you want to switch the comparison behavior to something custom (reference comparison or case-insensitivity) you can use Resharper to convert the anonymous type to a named class. Resharper can also generate equality members.

There is also a very practical reason to do this: Anonymous types are convenient to use as hash keys in LINQ joins and groupings. For that reason they require semantically correct Equals and GetHashCode implementations.

Leave a Comment