var keyword (or Implicitly Typed Local Variables)

Thursday, 17 April 2008

Posted by Sébastien Lachance with Comments (0)

If you are like me and installed the nightly build of Resharper 4, you might have seen the recommendation it made to use the keyword "var" almost everywhere. But why?

Here is my answer :

First of all, you must know that the keyword var is not like "Variant". It is not late-bound or loosely typed. The compiler will be able to infer the type from the right side of the expression. In many case, it's optional, but sometime you don't have a choice. It's the case with Anonymous Types :

var customer = new {ID = 1, Name = "Sebastien", CreditCardNumber = "You can dream!"};
 
It is also often seen with LINQ.
 
Should you use it everywhere you can? Well, it's a matter of preferences. Mine is to use it only when necessary. If the code is harder to understand when using var, then declare the variable explicitly.
 



blog comments powered by Disqus