When assigning the result of a query expression to a variable, there are cases when you do know the result typeand so the use of the var keyword is optional.
However, in some cases, an anonymous type is created to contain the results of the expression. In these cases, you must use the var keyword, because the correct type is generated internally by the compiler and not available to your code.
In the example below, we get something back that we can iterate on, but each element within the result set is anonymously typed, an object containing Name and Age fields.
1
2
3
4
5
6
| var oldDogs = from aDog in dogs where <span class="skimlinks-unlinked">aDog.Age</span> > 10 select new { <span class="skimlinks-unlinked">aDog.Name</span>, <span class="skimlinks-unlinked">aDog.Age</span> };foreach (var anOldie in oldDogs) Console.WriteLine(string.Format("{0}, age {1}", <span class="skimlinks-unlinked">anOldie.Name</span>, <span class="skimlinks-unlinked">anOldie.Age</span>)); |

