Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other than for LINQ queries, how do you use anonymous types in C#?

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?

like image 858
itsmatt Avatar asked Oct 03 '08 18:10

itsmatt


2 Answers

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.

like image 62
Bradley Grainger Avatar answered Sep 20 '22 22:09

Bradley Grainger


ASP.NET MVC routing uses these objects all over the place.

like image 29
yfeldblum Avatar answered Sep 23 '22 22:09

yfeldblum