I had an interesting conversation with a friend earlier this week, over when to use the var keyword in C# 3.0.

He and a colleague had divergent views, one passionately arguing it should be used whenever possible, and the other just as passionate in his view that it should never be used.

Interestingly, both were motivated by a keen desire to keep the code as readable as possible. One believed that the frequent repetition of type information introduced noise that distracted a reader from the task at hand, the other that removing the types was suppressing information the reader needed to know.

As usual, my own opinion sits somewhere in the middle between these two extremes.

I believe that both my friend and his colleague are concerned about the right things, and that both their arguments are correct.

Here are the guidelines I follow:

  • Use var to eliminate simple repetition of type information, reducing noise.

  • Don’t use var where its use would conceal a type that is important to understanding how the code operates.

The distinction here is critical – in any piece of code, some of the local variables are more important than others.

Some local variables are just carriers – ways to conveniently convey data from one place to another. They exist to because of the way the API has been designed, or to avoid evaluating common sub-expressions multiple times, or for any of a thousand technical reasons. But, fundamentally, they don’t matter to the algorithm.

On the other hand, some variables are crucial – they contain key pieces of information. Understanding what these variables hold, and when, is vital to understanding the algorithm.

Using var to suppress type information for carrier variables makes the code easier to understand.

Using var to suppress type information for crucial variables makes the code harder to understand.

The key is to understand which is which.


blog comments powered by Disqus
Next Post
Class Diagrams as Documentation  28 Mar 2009
Prior Post
Stages of Competence  22 Mar 2009
Related Posts
When (not) to use Var  16 Jul 2016
Semantic Types Redux  05 Jun 2016
Semantic Types in C#6  27 May 2016
Property Enhancements for C#  20 Dec 2015
Language Extensions for C#  19 May 2014
When should methods be Static?  09 Oct 2012
Of Method Naming and more  29 Sep 2012
Someone needs an intervention  16 Dec 2011
CallerInfo in C# 5  08 Dec 2011
Regions in C#  16 May 2011
More csharp posts »
Related Pages
March 2009 archive