views:

115

answers:

3

I understand that if I cast it to a named type I can do whatever I want with it, but it'd make for much tidier code if I could keep the anonymity between method calls.

+1  A: 

If you really want to be an asshole, you can do this: http://msmvps.com/blogs/jon_skeet/archive/2009/01/09/horrible-grotty-hack-returning-an-anonymous-type-instance.aspx

... But please don't!

John Rasch
Good old cast by example.
R0MANARMY
That's just nasty!
Brian Gideon
+1  A: 

Think of the signature of your method as a contract. Your method says "I promise to return you something that contains the following fields." If you return an anonymous object from your method, there's no contract. You're just saying "There's some data here, good luck!"

If C# 4 is at all an option, you can just use tuples to return somewhat more arbitrary data.

R0MANARMY
Same answer I gave to Ben: It's certainly possible for the compiler to generate a class behind-the-scenes and use all the existing type-verifications afterwards...
BlueRaja - Danny Pflughoeft
@BlueRaja The Green Unicorn: It is possible for the compiler to figure that out behind the scenes, and (for example) F# compiler is able to figure out types from your code (or you get a type error). Doesn't change the fact that the C# compiler (as of right now) doesn't do that.
R0MANARMY
A: 

This is a guess...but I'm so "awesome" I'm "sure" I'm right...

Anonymous types really aren't "anonymous." The class that represents the unknown type is generated at run-time local to the method call on the run-time stack(hence the method-only scope). Returning from the function call(popping the stack) you lose all the objects in that scope including the anonymous class that was hiding on the stack with that method call.

Guessing over...

Achilles
Anonymous types are generated at compile-time. The difference is that they are private to the scope they were created in.
Rex M
Anonymous classes are generated at compile time. http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx That's why John Rasch's "cast by example" example works.
R0MANARMY
Sorry, your guess is wrong: Anonymous types are created at compile-time. You can verify this using Reflector. You can also pass and return anonymous type instances as `object` and play with them using reflection, but I wouldn't recommend it in production code.
LukeH
@Rex M: They aren't private classes, they are `public sealed` (at least for now)
R0MANARMY
Good ole guessing...fails me again lol.
Achilles