Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are anonymous types in .NET implemented as reference type?

Because an anonymous type is readonly anyway, is would be more efficient if they implemented them as structs so that linq queries doesn't need to create tons of temporary objects:

// This doesn't make any sense, it is just for demonstration
var result = thingies
.Select(x=> new {A = 1, B = 2, C = 3});

Btw. I got this idea, when reading this

EDIT:

The greatest thing would be if the compiler would, depending on the size and usage of the variable (must if be passed to lots of methods), decide whether to make if a value type or reference type.

But could the following sentence which I found in the msdn cause problems then:

If two or more anonymous types in the same assembly have the same number and type of properties, in the same order, the compiler treats them as the same type.

Since an anonymous object (with its associated type) cannot leave the method which it is defined in we have no problems here, do we?

like image 702
codymanix Avatar asked Aug 18 '11 14:08

codymanix


1 Answers

The full .NET garbage collector is particularly well-optimized for two cases: large, long-lived objects that last significant amounts of time, and small, short-lived objects that die off quickly. Gen0 collections are practically free given how fast they are (so fast and frequent, in fact, that many profilers don't even bother showing them or their contents), so there's little reason to avoid temporaries that will be gone within the scope of the function that created them.

Anonymous types fit the second case almost perfectly; they're not meant to outlive the function that creates them (although you can do it with some trickery). Given this model, and given the fact that most value types are relatively expensive to copy around, and given that many LINQ queries involve a long chain of functions that would all require yet another copy, it makes sense to me that the designers chose to make them reference types.

like image 99
MikeP Avatar answered Oct 03 '22 13:10

MikeP