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.
Usually you have to resort to a helper method.
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.