#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.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #804 – Tradeoffs when Using the var Keyword

  1. Matt Freiburg says:

    While I a hardened advocate of the var keyword simply for the sake of coder productivity gains, I can appreciate when it’s overused to the point of diminished readability.

    What I’d love to see is an ability for the IDE to “auto-correct” my use of the var keyword after I terminate a line of code with a semicolon. That is, in cases when the type is compiler-derivable (i.e. not anonymous types), change this:

    var oldDogsNames = db.GetDogs().Select(d=>d.Name);

    to this:

    IEnumerable oldDogsNames = db.GetDogs().Select(d=>d.Name);

    when I type that last semicolon or some other such termination event.

    Don’t break my stride coding, and auto-enhance my code’s future readability, thank you.

  2. Pingback: Interesting .NET Links - March 21 , 2013 | TechBlog

Leave a comment