C# – Creating anonymous class as custom key in dictionary

anonymous-classcdictionarynet

While using dictionary, i always override GetHashCode and Equals ( or provide a custom comparer to the dictionary).

What happens behind the covers when i create an anonymous class as key?

Sample Code….

 var groups=(from item in items
                 group item by new { item.ClientId, item.CustodianId, item.CurrencyId }
                   into g
                   select new {
                     Key=g.Key,                     
                     Sum=g.Sum(x => x.Cash)
                   }).ToDictionary(item=>item.Key,item=>item.Sum);

This code gives me the expected result, but i am not providing GetHashCode and Equals method for the anonymous class.
Shouldn't this code fail to group my items on the basis of items in anonymous class??

Best Answer

Nope - the anonymous class automatically generates appropriate Equals/GetHashCode implementations.

From the C# language spec, section 7.5.10.6:

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.