Why use var

date_range  08 May 2014

.Net Development

Whilst looking through some of my code today someone was asked why I was using var for all my local variable declarations. The var keyword was added to C in version 3.0 to support anonymous types within the scope of methods. When you declare a variable with var you are invoking implicit typing. The opposite of this when you declare using the type name such as string is called explicit typing as you are definitively informing the compiler that this variable will be of this type. When a variable is declared with var the compiler infers from context the type you are intending to use. Which ever typing pattern you employ the IL will end up exactly the same.

  var thing = "Hello";
  string thing = "Hello";

To the compiler we have produced exactly the same code. So why use it?

The answer I came up with was, “Well thats what I was taught to do so I’ve always done it.” Not a particularly great answer huh.. So I continued. “In terms of readability when mixing the use of anonymous types dynamic objects and classes using implicit typing everywhere makes the code more consistent.”

The bit of code we were looking at was the result of a ToString() method and what I wish I would have said at this point was that holding the result in a var has not made the code any less readable. The method is very clearly named and obviously implies that the result will produce a string. Declaring the variable as a string would have made the code unnecessarily slightly more verbose. If we take another common use of local variables construction:

Thing thing = new Thing();
var thing = new Thing();

What have we gained by explicitly declaring the type? Not a huge amount in my opinion as the type is inferred not 20 characters away. If youre writing good OO code the scope of the variable wont exceed more than a few lines either as your method will be concise and cohesive.

In conclusion its a preference thing as with the majority of coding standards they are the result of deliberation of a community. When writing code that only I am going to be maintaining I prefer var as it can make refactoring that little bit quicker sometimes. It also makes me more conscious of my naming technique for variables and methods. Some people say that it encourages Hungarian notation for example but I’ve not seen this in practice. Use what youre comfortable with but please PLEASE be consistent!

comments powered by Disqus

chevron_left Archive