While analyzing some ASP.NET MVC projects I got to see anonymous types scattered all over.
HTML helpers have them:
<%=Html.TextBox("view.Address", "address", new { Class = "text_field" })%>
A lot of the return types for actions have them:
JsonNetResult jsonNetResult = new JsonNetResult
{
Formatting = Formatting.Indented,
Data = new {Something= “”}
}
I know this came from LINQ:
from p in context.Data
select new { p.Name, p.Age };
Are these really the correct way to accomplish things now outside of LINQ? Do they hurt code reusability and readability?
IMHO, the biggest problems with anonymous types stem from the inability to name their type. That is, it's not possible to expilictly specify the type of an anonymous type as an expression in code. This really makes in awkward to do things like create a generic List.
var list = New List<No way to specify an Ananymous type>();
Usually you have to resort to a helper method.
public List<T> CreateList<T>(T notUsed) {
return new List<T>();
}
var list = CreateList(new { .Class = "foo" });
This also has a larger impact in that you can't use an anonymous type as a return type, makes casting extremely awkward (need a helper method), etc ...
But these are not the operations that Anonymous Types were designed for. In many ways they are designed to used within a particular defined function and it's subsequently created lambda expressions. Not as a data communication type between to full fledged functions. This is certainly a limitation in the design and at times drives me batty. But overall I find them to be a very useful construct in the language.
Many parts of LINQ would not be possible without them in some form.
When the object being created is a transitory object, i.e., it's immediately consumed or converted into something else, I like the idea of anonymous types. It prevents you from littering your code with single-purpose classes whose only use is as a short-lived container. Your examples are typical of the types of uses where it comes in handy, i.e., in the helper extensions it's almost always immediately converted into a parameter dictionary and with the json result it gets serialized. If the class has domain significance or needs to be used as a first-class object, then by all means create a domain class for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With