Testing Anonymous Type Equality
Anonymous type equality is defined very deliberately. If any two or more anonymous types have the same order, number, and member declaratory type and name, the same anonymous type class is defined. In this instance, it is permissible to use the referential equality operator on these types. If any of the order, number, and member declarator type and name is different, a different anonymous type definition is defined for each. And, of course, testing referential integrity produces a compiler error.
If you want to test member equality, use the Equals method (defined by all objects). Anonymous types with the same order, type, and name, type, and value of member declarators also produce the same hash; the hash is the basis for the equality test. Listing 1.13 provides some samples of anonymous types followed by equality tests and comments indicating those that produce the same anonymous types and those that have memberwise equality.
Listing 1.13. Various Anonymous Types with Annotations
var audioBook = new {Artist="Bob Dylan", Song="I Shall Be Released"}; // anonymous type 1 var songBook1 = new {Artist="Bob Dylan", Song="I Shall Be Released"}; // also anonymous type 1 var songBook2 = new {Singer="Bob Dylan", Song="I Shall Be Released"}; // anonymous type 2 var audioBook1 = new {Song="I Shall Be Released", Artist="Bob Dylan"}; // anonymous type 3 audioBook.Equals(songBook1); // true everything the same audioBook.Equals(songBook2); // first member declarators different songBook1.Equals(songBook2); // member declarator-names differ audioBook1.Equals(audioBook); // member declarators in different orders
The anonymous types audioBook and songBook1 produce the same anonymous type. These are the only two that produce the same hash and, as a result, the Equals method returns true. The other anonymous types are similar, but either the member declarators are different—songBook1 uses the member declarator Artist and songBook2 uses Singer—or the order of the declarators are different—referring to audioBook and audioBook1.