Why does the Equals implementation for anonymous types compare fields?
Solution 1:
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.
Solution 2:
For the why part you should ask the language designers...
But I found this in Eric Lippert’s article about Anonymous Types Unify Within An Assembly, Part Two
An anonymous type gives you a convenient place to store a small immutable set of name/value pairs, but it gives you more than that. It also gives you an implementation of Equals, GetHashCode and, most germane to this discussion, ToString. (*)
Where the why part comes in the note:
(*) We give you Equals and GetHashCode so that you can use instances of anonymous types in LINQ queries as keys upon which to perform joins. LINQ to Objects implements joins using a hash table for performance reasons, and therefore we need correct implementations of Equals and GetHashCode.
Solution 3:
The official answer from the C# Language Specification (obtainable here):
The Equals and GetHashcode methods on anonymous types override the methods inherited from object, and are defined in terms of the Equals and GetHashcode of the properties, so that two instances of the same anonymous type are equal if and only if all their properties are equal.
(My emphasis)
The other answers explain why this is done.
It's worth noting that in VB.Net the implementation is different:
An instance of an anonymous types that has no key properties is equal only to itself.
The key properties must be indicated explicitly when creating an anonymous type object. The default is: no key, which can be very confusing for C# users!
These objects aren't equal in VB, but would be in C#-equivalent code:
Dim prod1 = New With {.Name = "paperclips", .Price = 1.29}
Dim prod2 = New With {.Name = "paperclips", .Price = 1.29}
These objects evaluate to "equal":
Dim prod3 = New With {Key .Name = "paperclips", .Price = 1.29}
Dim prod4 = New With {Key .Name = "paperclips", .Price = 2.00}
Solution 4:
Because it gives us something that's useful. Consider the following:
var countSameName = from p in PersonInfoStore
group p.Id by new {p.FirstName, p.SecondName} into grp
select new{grp.Key.FirstName, grp.Key.SecondName, grp.Count()};
The works because the implementation of Equals()
and GetHashCode()
for anonymous types works on the basis of field-by-field equality.
- This means the above will be closer to the same query when run against at
PersonInfoStore
that isn't linq-to-objects. (Still not the same, it'll match what an XML source will do, but not what most databases' collations would result in). - It means we don't have to define an
IEqualityComparer
for every call toGroupBy
which would make group by really hard with anonymous objects - it's possible but not easy to define an IEqualityComparer for anonymous objects - and far from the most natural meaning. - Above all, it doesn't cause problems with most cases.
The third point is worth examining.
When we define a value type, we naturally want a value-based concept of equality. While we may have a different idea of that value-based equality than the default, such as matching a given field case-insensitively, the default is naturally sensible (if poor in performance and buggy in one case*). (Also, reference equality is meaningless in this case).
When we define a reference type, we may or may not want a value-based concept of equality. The default gives us reference equality, but we can easily change that. If we do change it, we can change it for just Equals
and GetHashCode
or for them and also ==
.
When we define an anonymous type, oh wait, we didn't define it, that's what anonymous means! Most of the scenarios in which we care about reference equality aren't there any more. If we're going to be holding an object around for long enough to later wonder if it's the same as another one, we're probably not dealing with an anonymous object. The cases where we care about value-based equality come up a lot. Very often with Linq (GroupBy
as we saw above, but also Distinct
, Union
, GroupJoin
, Intersect
, SequenceEqual
, ToDictionary
and ToLookup
) and often with other uses (it's not like we weren't doing the things Linq does for us with enumerables in 2.0 and to some extent before then, anyone coding in 2.0 would have written half the methods in Enumerable
themselves).
In all, we gain a lot from the way equality works with anonymous classes.
In the off-chance that someone really wants reference equality, ==
using reference equality means they still have that, so we don't lose anything. It's the way to go.
*The default implementation of Equals()
and GetHashCode()
has an optimisation that let's it use a binary match in cases where it's safe to do so. Unfortunately there's a bug that makes it sometimes mis-identify some cases as safe for this faster approach when they aren't (or at least it used to, maybe it was fixed). A common case is if you have a decimal
field, in a struct, then it'll consider some instances with equivalent fields as unequal.