tags:

views:

114

answers:

5

What is the design decision to lean towards not returning an anonymous types from a method?

+7  A: 

You can return an instance of an anonymous type from a method - but because you can't name it, you can't declare exactly what the method will return, so you'd have to declare that it returns just object. That means the caller won't have statically typed access to the properties etc - although they could still pass the instance around, access it via reflection (or dynamic typing in C# 4).

Personally I would quite like a future version of C# to allow you to write a very brief class declaration which generates the same code (immutable properties, constructor, Equals/GetHashcode/ToString) with a name...

There is one grotty hack to go round it, called casting by example. I wouldn't recommend it though.

Jon Skeet
...you can have that with CodeRush today, very handy. Is there any reason you want this to be included in the language rather than VS?
Johannes Rudolph
@Johannes: Yes, maintainability. I want to be able to maintain the *simple* form. The *ability* to expand the type into its full code so I can then add extra functionality is certainly handy, but there's more to it than that. To give another example, imagine if we didn't have the `using` statement, but VS macros which would generate the equivalent try/finally blocks - would that be just as good as having the using `statement` in the language, in your view?
Jon Skeet
@Jon: Sounds reasonable. So you're basically proposing a "data only class" construct?
Johannes Rudolph
@Johannes: Yup. Possibly in an *ideal* world you could then add extra methods (but not fields) without expanding it - although extension methods would do the same thing, of course.
Jon Skeet
+1  A: 

Because an anonymous type has no name. Therefore you cannot declare a return type for a method.

Developer Art
So you would use 'var'
Henk Holterman
+1  A: 

Because C# is statically typed language and in a statically typed language the return type of a method needs to be known at compile time and anonymous types have no names.

Darin Dimitrov
+1  A: 

How can you use your type inside your method if the definition is only in the call of the method ?

It's not javascript.

remi bourgarel
I don't see you you got from the question to this answer...
Jon Skeet
A: 

At least up to 3.5, anonymous types are actually resolved at compile time, and this would be impossible (or quite hard) to do with anonymous method signatures.

giorgian