#805 – An Example of Discretionary Use of the var Keyword

Below is one example where you may or may not want to use the var keyword.

            var oldDogs = from aDog in dogs
                          where aDog.Age > 10
                          select aDog.Name;

            foreach (var next in oldDogs)
                Console.WriteLine(next);

This works just fine.  We don’t specify the type of the value returned from the query expression, but we know that it’s something that we can iterate on, so we just use var for the result and then var again in the foreach.

The difficulty comes when someone else is going to modify this code.  The query actually returns an enumerable list of strings.  But reading the code, you might make the mistake of thinking that it returns a list of dogs.

We could have been more clear by writing:

            IEnumerable<string> oldDogs = from aDog in dogs
                          where aDog.Age > 10
                          select aDog.Name;

            foreach (string name in oldDogs)
                Console.WriteLine(name);
Advertisements