I've been trying to get up to speed on some of the newer features in C# and one of them that I haven't had occasion to use is anonymous types.
I understand the usage as it pertains to LINQ queries and I looked at this SO post which asked a similar question. Most of the examples I've seen on the net are related to LINQ queries, which is cool. I saw some somewhat contrived examples too but not really anything where I saw a lot of value.
Do you have a novel use for anonymous types where you think it really provides you some utility?
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.
ASP.NET MVC routing uses these objects all over the place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With