views:

871

answers:

8

I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?

+1  A: 

When you create types for 'Use and throw' purposes. This seems to have come due to LINQ. Seems to be a way to create structures with fields on the fly for a LINQ query. Returning a struct/type with specified fields only. If not for this, you'd have to declare a .Net type for each unique combination of fields you wish to retrieve.

Gishu
+5  A: 

From LINQ in action (page 76 section 2.6.3):

... anonymous types [are] a great tool for quick and simple temporary results. We don't need to declare classes to hold temporary results thanks to temporary types.

basically they're useful to hold information in the local scope temporarily. Anything more requires the use of reflection and can become quite a problem. The example they give in the above-quoted book is in writing to console the id, name, and amount of memory taken up by each running process. They create an anonymous type, add it to a list (all one statement) and then use ObjectDumper to output it. Therefore the code no longer needs a separately declared class to hold the id, name and memory used but its all declared implicitly bringing the line count down to 4:

var pl = new List<Object>();
foreach(var p in Process.GetProcesses())
  pl.Add(new {p.Id, p.ProcessName, Memory=p.WorkingSet64});
ObjectDumper.Write(pl);
George Mauer
+8  A: 

Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding.

I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method.

For instance:

var query = from item in database.Items
            // ...
            select new { Id = item.Id, Name = item.Name };

return query.ToDictionary(item => item.Id, item => item.Name);

Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class.

Omer van Kloeten
Do you EVER need this. Surely if your doing so much in your method that it warrants an anonymous type then you should refactor the method. In your example you query the DB and then modify the results,..that's 2 separate methods for me.
Stimul8d
I'm not modifying the results, I'm transmuting them into some other form that's easier to return.One should be careful to not over-distribute their code over multiple methods because that would make the code completely unreadable and create, since there's no ability to use anonymous types, a lot of either ugly code or redundant manually-coded types.
Omer van Kloeten
+1  A: 

Use them with Linq.

Registered User
A: 

The most popular use of anonymous types are for specifying projections in a LINQ to SQL query.

This query

from x in db.Table1 select new {x.Column1, Alias2=x.Column2}

will be converted to this SQL:

SELECT Column1, Column2 AS Alias2 FROM Table1

With anonymous types, you can create ad hoc projections without defining the type for it beforehand. The compiler will define the type for you.

Mark Cidade
A: 

It is important to know, that LINQ doesn't force you, to use anonymous types. You can also write normal object constructions after select.

var query = from item in database.Items // ... select new Person(item.id, item.Name)

This prevents you from ugly reflection programming.

ChaosSpeeder
A: 

@ChaosSpeeder: unfortunately LINQ To Entities only supports parameterless constructors

Wouter
+1  A: 

@Wouter :

var query = from item in database.Items
select new Person
{
ID =item.id,
NAME= item.Name
};

where ID and NAME are real property of your Person class.