With a bit of reflection, you can turn an anonymous type into a Dictionary<string, object>; Roy Osherove blogs his technique for this here: http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx
Jacob Carpenter uses anonymous types as a way to initialize immutable objects with syntax similar to object initialization: http://jacobcarpenter.wordpress.com/2007/11/19/named-parameters-part-2/
Anonymous types can be used as a way to give easier-to-read aliases to the properties of objects in a collection being iterated over with a foreach
statement. (Though, to be honest, this is really nothing more than the standard use of anonymous types with LINQ to Objects.) For example:
Dictionary<int, string> employees = new Dictionary<int, string>
{
{ 1, "Bob" },
{ 2, "Alice" },
{ 3, "Fred" },
};
// standard iteration
foreach (var pair in employees)
Console.WriteLine("ID: {0}, Name: {1}", pair.Key, pair.Value);
// alias Key/Value as ID/Name
foreach (var emp in employees.Select(p => new { ID = p.Key, Name = p.Value }))
Console.WriteLine("ID: {0}, Name: {1}", emp.ID, emp.Name);
While there's not much improvement in this short sample, if the foreach
loop were longer, referring to ID
and Name
might improve readability.