Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating anonymous class as custom key in dictionary

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??

like image 319
Manish Basantani Avatar asked Jan 29 '10 09:01

Manish Basantani


People also ask

How to declare anonymous type?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

How to create anonymous type object in C#?

You create an anonymous type using the new operator with an object initializer syntax. The implicitly typed variable- var is used to hold the reference of anonymous types. The following example demonstrates creating an anonymous type variable student that contains three properties named Id , FirstName , and LastName .

When can anonymous types be created C#?

In C#, you are allowed to create an anonymous type object with a new keyword without its class definition and var is used to hold the reference of the anonymous types. As shown in the below example, anony_object is an anonymous type object which contains three properties that are s_id, s_name, language.

When you define an anonymous type the compiler converts the type into?

The compiler generates a name for each anonymous type. If two or more anonymous type objects are defined in the same assembly and the sequence of properties are same in terms of names and types than the compiler treats both as same object instances of type.


1 Answers

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.

like image 52
Jon Skeet Avatar answered Sep 24 '22 05:09

Jon Skeet