views:

176

answers:

8

I've read some articles on how to create anonymous types in C#.

What are some use cases for these things? To me, it seems like it might make things a little more difficult to understand declaring objects and their members inline.

When does it make sense to use Anonymous Types?

+3  A: 

I often use them when databinding to complex controls -- like grids. It gives me an easy way to format the data I'm sending to the control to make the display of that data easier for the control to handle.

GridView1.DataSource = myData.Select(x => new {Name=x.Description, Date = x.Date.ToShortDate() });

But, later on, after the code is stable, I will convert the anonymous classes to named classes.

I also have cases (Reporting Services) where I need to load them using non-relational data, and Reporting Services requires the data to be FLAT! I use LINQ/Lambda to flatten the data easily for me.

Chris Brandsma
+3  A: 

I like to use anonymous types when I need to bind to a collection which doesn't exactly fit what I need. For example here's a sample from my app:

    var payments = from terms in contract.PaymentSchedule
                   select new
                   {
                       Description = terms.Description,
                       Term = terms.Term,
                       Total = terms.CalculatePaymentAmount(_total),
                       Type=terms.GetType().Name
                   };

Here I then bind a datagrid to payments.ToList(). the thing here is I can aggregate multiple objects without havign to define an intermidary.

JoshBerke
A: 

They are useful when using LINQ

var query = from c in listOfCustomers
            select new {FirstName = c.Name,c.City};

Have a look at this Introduction to LINQ

Russ Cam
A: 

Here is a good blog post by Charlie Calvert about the uses of Anonymous types.

JTA
+1  A: 

I find them to be a very useful replacement for simple struct/structure objects, especially when working with VB.NET since it does not support auto-implemented properties.

STW
+1  A: 

LINQ/Lambda's

 var quantity = ...
 var query = db.Model.Select( m => new
                                  {
                                    Name = m.Name,
                                    Price = m.Price,
                                    Cost = M.Price * quantity
                                  } );
 foreach (var q in query)
 {
     Console.WriteLine( q.Name );
     Console.WriteLine( q.Price );
     Console.WriteLine( q.Cost );
 }

ASP.NET MVC -HtmlHelpers or when returning JSON

<%= Html.TextBox( "Name", Model.Name, new { @class = "required" } ) %>

public ActionResult SearchModels( var q, int limit )
{
     var query = db.Models.Where( m => m.Name.StartsWith( q ) )
                          .Take( limit )
                          .Select( m => new { m.DisplayName, m.Name, m.ID } );

     return Json( query.ToList() );
}

Actually, pretty much anywhere you just need a temporary container type for a short-lived action.

tvanfosson
A: 

Personally, I don't find much use for anonymous types. They're certainly to be used with a degree of caution at the least. The situation in which they are typically are used are when creating LINQ queries that reteurn multiple values, and you only need to utilise the queried data for the duration of the function. (If the data needs to be used outside, then anonymous types can't be used - you need to declare your own, and for good reason, i.e. readability.) More generally, they can sometimes be useful when using plain lambda expressions, though again I myself have required them very infrequently. (When I say required, there are almost alternatives depending on the context, but sometimes anonymous types are in fact the most elegant option.) If you'd like a code example, just let me know and I'll try to come up with one with some reasonably decent application.

Noldorin
+1  A: 

from the horse's (Microsoft's) mouth:

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type.

Anonymous Types are useful in areas that you would usually use a defined structure but don't want to because it will only be used within a limited scope. I tend to use them as data sources or as containers for aggregate (sum, count, etc) values.

Jeremy