views:

249

answers:

3

There doesn't seem to be any way as anonymous types derive from object. But I thought I'd ask since much of the time we use anonymous types in simple query expressions to extract subsets of data to be used in those anonymous types we create. It just seems to me they should be structs (value types) for greater memory efficiency vs. reference types.

Thoughts?

+16  A: 

No there is no supported C# syntax which will produce anonymous structs

JaredPar
Sigh. Bummer dood. {-o)
Boydski
+3  A: 

Have you profiled your app and found anonymous types to be the slowest part of it? If so, I suggest you manually create the needed structs and re-test to see if that fixed your problem. Otherwise, I'd spend more time worrying about the business problem at hand and less time typing (like the feature allows).

No Refunds No Returns
Sorry, didn't meant to imply there were any problems. Not at all. I'm just always looking for ways to ease the burden on the GC as a matter of principle. Any time I can put stuff on the stack, I do. Simple types that are just there as simple data transports would be best served to be on the stack.
Boydski
+11  A: 

There seems to be this commonly-held idea that value types are "more efficient" than reference types. This is entirely mythical; they are more efficient for some operations and less efficient for others.

For example, large value types are less efficient compared to reference types if the unit of work you are concerned about is the "copy the value to a new location" work. A reference type copies a pointer-sized reference irrespective of the size of the referred data and therefore copies in a single highly optimized machine instruction. A value type copies the size of the data every single time, which can be quite large and take multiple instructions.

Regardless, anonymous types are solely a convenience feature. If you don't like their performance characteristics, you don't have to use them. You can define your own struct if you'd rather.

Eric Lippert
Sorry Eric. The question could've been more elegant. I'm fully aware this revolves around context. One must always use wisdom when choosing value vs. reference types for more complex functionality. But most examples of anon types I've seen are constantly creating and destroying small instances of objects (between 3 and 5 member values or so); the object being used as a mere transport of simple data on Gen 0 of the heap. It's obviously more costly than doing so on the stack. I like the sugary convenience of anonymous types. But it would still be great to be able to choose between ref vs. value.
Boydski