Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some examples of how anonymous types are useful?

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?

like image 579
Mithrax Avatar asked Apr 21 '09 20:04

Mithrax


1 Answers

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.

like image 184
JoshBerke Avatar answered Sep 20 '22 20:09

JoshBerke