2

Possible Duplicate:
How should anonymous types be used in C#?

What are anonymous types in C#, and when should they be used?

Community
  • 1
  • 1
CJ7
  • 22,579
  • 65
  • 193
  • 321

2 Answers2

3

Anonymous types are types created on the fly typically in order to return results in a LINQ statement. Here's an example from MSDN

var productQuery = 
    from prod in products
    select new { prod.Color, prod.Price };

A new type with the read-only properties Color and Price is created and the query returns instances of this type when enumerated.

foreach(var product in productQuery) {
    Console.WriteLine(product.Color);
}

product will be of the anonymous type defined above.

Anonymous types are useful for returning several properties from a query without having to define a type explicitly for that purpose.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
  • You could also just go: var product = new { Color = "Red", Price = 42m } That is, it doesn't have to be in a LINQ statement. – Steffen May 16 '10 at 09:35
  • @Steffen: I know, but the OP wanted to know when to use anonymous types. In my experience LINQ is the obvious use case. – Brian Rasmussen May 16 '10 at 09:37
2

Straight from the horse's mouth: http://msdn.microsoft.com/en-us/library/bb397696.aspx

In silico
  • 51,091
  • 10
  • 150
  • 143