views:

94

answers:

3

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

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

+1  A: 

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

In silico
+1  A: 

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
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
@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
A: 

Possible duplicate: http://stackoverflow.com/questions/48668/how-should-anonymous-types-be-used-in-c

boj
This is a comment.
Oskar Kjellin
@boj: that question does not contain answers that are good enough for me
Craig Johnston