#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);
Advertisement

#804 – Tradeoffs when Using the var Keyword

You’d most often use the var keyword, indicating an implicit type, in the following situations:

  • For anonymous types  (var is required)
  • As the type of the result of a LINQ expression
  • To avoid duplicating a long type name

You should end up using var if its use is required (for anonymous types) or if using var improves the readability of your code.

You must be careful, however, in using var to simplify your code.  In many cases, while its use may make writing your code easier, the omission of a type can make the code less readable, because the person later reading the code may need to first determine the variable’s type before being able to use it.

A good rule of thumb is to use strongly typed variables by default and only use var when it is necessary.