Friday, January 15, 2010

Using (and Abusing) The var C# 3.5 Keyword

The quote from this MSDN article (Implicitly Typed Local Variables) below (emphasis mine) spells out how I feel about the var keyword, which is defined in the var (C# Reference,) also on MSDN.

"Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types."

I use var as Microsoft's C# design team intended -- in cases where I need it and nothing else will work.  There is no reason to go crazy and look at "var" as a shortcut or simplification of the language.

I have reviewed (and rejected) code from var happy C#s (CodePlex) ... it just isn't worth it down the road.  If the compiler has to infer the type, so does the maintainer.

Furthermore, overuse of the var keyword has some nasty side effects, which have been blogged about: