views:

190

answers:

6

What are the best use cases for anonymous types?

It would seem to me that they are only useful within a limited context, for example one class or one function. They can hardly be used outside of this context, because without reflection no one will know what properties are available on these types.

A: 

Correct; they are only practical within an extrememly limited scope.

Jason Watts
Do you know of any good use cases?
Josh G
+2  A: 

However, it doesn't stop e.g. the ASP.NET MVC Team you use them as a Hashtable-style parameter object...

Url.Action(new{controller="Home", action="Index"})

Which I wouldn't encourage, though, because of heavy use of magic strings.

I almost exclusively use anonymous types in LINQ-statements where in the same method you iterate over the resultset. That is pretty much why they were introduced

flq
+4  A: 

Anonymous types are intended to only be used in very narrow scopes. Most use cases that I've had for them involve Linq.

var result = from x in MyCollection
             select new 
             {
                 x.Prop1, 
                 x.Prop2
             };

Also, in the case of Linq to SQL - using anonymous types will generate different SQL by selecting only the columns that are used in the anonymous type. In the case above (if it were a Linq to SQL query), it would generate something like "select prop1, prop2 from mytable" instead of selecting all of the fields.

I've never run across (yet) a situation where I wanted to just declare a new anonymous type in my code. I suppose if anything else, maybe it would be a good use for local constants?

var x = new
        {
            FirstName = "Scott",
            LastName = "Ivey"
        };
Scott Ivey
Hmmm... Local constants is an interesting idea. Yes, I've heard of them used with LINQ queries, but it never seemed helpful to me yet.
Josh G
+1  A: 

They're useful anytime you want to run a query over some objects and then do some other operation on them (like iterate).

For example:

var procs = System.Diagnostics.Process.GetProcesses().Select(p => new { p.Id, p.ProcessName});
foreach(var p in procs)
{
    Console.WriteLine("{0}: {1}", p.Id, p.ProcessName);
}
Jonathan
I find often in these situations that I already have an object that I am selecting from. Why wouldn't I just select the whole object unless it was a join()?
Josh G
Iterating over the projection (anon class) may be less expensive than carrying around properties you don't care about.
John Saunders
Makes sense. Thanks!
Josh G
+1  A: 

I have had a lot of luck with them lately in satisfying fields in DataGrids or DataViews that depend on columns from queries that no longer return the same data. For example, sometimes data sources were normalized or fields renamed for various reasons. Using a LINQ query returning anonymous types as a 'front-end' we're able to keep exisitng grids in production.

n8wrl
The existing grids are kept in production because the anonymous types have the same properties/interface that the old data did?
Josh G
Yes - queries used to come back in datasets with specific columns. Over time those columns changed or objects were implemented to provide the same functionality but without the same property names. Selecting from collections of these objects projecting onto anon types keeps us from having to muck with the grids.
n8wrl
+2  A: 

One case which I have found the anonymous type to be useful is in serializing objects to JSon and returning them in ASP.NET MVC actions. You don't necessarily want to return all properties of an object and an anonymous type can help you with this..

[AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Person(int id)
    {
        Person person = manager.GetPersonById(id);
        if(Request.IsAjaxRequest())
            return Json(new {Name=person.Name, Age=person.Age,...});
        else
            ...
    }
markt