For me the benefit of using them is that
- You don't have to maintain another class for a small local calculation.
- You make the code more readable, concentrating on the tasks instead of the syntax.
- You don't have a class someone can abuse for their own purposes.
The example below introduces a couple of other ideas such as Linq but we can ignore them for now. From a list of Dogs the name property alone is selected (mapped) into an anonymous object and returned as a collection.
If I recall, what the compiler nicely does for you is to create a class for you in the background that you don't see. We can check this by using the ILDASM tool that comes with Visual Studio. If you see the picture below after I load my dll into there, the anonymous type has been created as a class called AnonymousType_0`1<T0> and you can see the property Name on there as well. It's worth noticing here that the property Name is readonly meaning that the anonymous type is immutable once you have created it. Immutability is something very dear to me being a fan of F# as well as BASIC languages.