When to not cast to Anonymous types

I was doing some tests on LINQ over DataTables where I was selecting into a new anonymous type. The code was quite simple, just doing a basic select.

 

var res = from n in contacts.Contact

   where n.LastName.StartsWith("L")

               select new {n};

 

 

Looking at the debugger, res is a WhereIterator, where the type that is being iterated over is the anonymous type that was created in the “select new {n}” portion of the LINQ query.

 

I then wanted to do something to each instance of the returned collection, which I would usually use a foreach statement for.

 

foreach (object o in res) {

            DoSomething(o.n); // error!

}

 

Of course, this works fine, but I don’t have access to the anonymous type’s member, which contains my data! After some thought and digging around, I realized that the key is to use the magical var type.

 

foreach (var o in res) {

            DoSomething(o.n); // Looks good!

}

 

Very excellent, you get the love of non-typed variables, all while having full type goodness. It's a great use for all those CPU cycles!