#806 – An Example of Mandatory Use of the var Keyword

When assigning the result of a query expression to a variable, there are cases when you do know the result type and 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.

            var oldDogs = from aDog in dogs
                                          where aDog.Age > 10
                                          select new { aDog.Name, aDog.Age };

            foreach (var anOldie in oldDogs)
                Console.WriteLine(string.Format("{0}, age {1}", anOldie.Name, anOldie.Age));
Advertisement