How should anonymous types be used in C#?

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.


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);

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.


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.