Reputation: 4537
What is the design decision to lean towards not returning an anonymous types from a method?
Upvotes: 2
Views: 471
Reputation: 273169
A lot of answers heere seem to indicatie that it is not possible because of the current syntax and rule. But the question is about changing them. I think it would be possible, but a little complicated and resulting in an awkward (error-prone) syntax. Like
var f() { return new { A = "*", B = 1 }; }
var x = f();
The question is whether this adds sufficient value to the language to make it worth it.
Upvotes: 1
Reputation: 3825
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.
Upvotes: 0
Reputation: 9389
How can you use your type inside your method if the definition is only in the call of the method ?
It's not javascript.
Upvotes: 1
Reputation: 1038710
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.
Upvotes: 1
Reputation:
Because an anonymous type has no name. Therefore you cannot declare a return type for a method.
Upvotes: 1
Reputation: 1499770
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.
Upvotes: 6