When first I saw the var keyword in C# 3.0 I was excited, my body tingling with excitement for the possibilities this keyword would bring to the world of many a .NET developer: Productivity, clarity, fame, and fortune. Unfortunately now that C# 3.0 has been with us for a while I feel that I must warn the public of the evil that is the var keyword. Productivity, clarity, fame, and fortune have succumbed to mind boggling spaghetti code, confusion, and lets be honest fame and fortune were never really on the table to begin with :)
What then is this evil of which I speak? Massive overuse of the var keyword. Observe the following hot dish of spaghetti bolognese:
1: public void SpaghettiBolognese()
3: var calculator = new Calculator();
4: var taxLevel = GetTaxLevels();
5: var person = GetPerson();
6: var tax = calculator.CalculateTaxLevel(person, taxLevel);
8: person.Tax = tax;
All kidding aside this piece of code breaks one of my most fundamental rules when reading and writing code: Don't make me think. Grokking a piece of code is though enough as it is having to keep types and varibles in memory (read: the developer brain) will slow down the process of code reviewing or debugging a piece of code.
For now I'm using a couple of rules to keep the var silliness at manageable levels.
1) Always use proper types for variables which are set from a method or property. It makes the code so much more readable.
1: Tax tax = calculator.CalculateTaxLevel(person, taxLevel);
2) Do use the var keyword when there is no question about which type it will be inferred to.
1: var calculator = new Calculator();
2: var i = 100;
3: var s = "Søren";
While the var keyword does offer a nice productivity gain it's important to realize when to use and more importantly when not to use it. Also it would seem that the var keyword is in cahoots with the good folks at Jetbrains as ReSharper is very eager to convert perfectly well formed type declarations to implicitly typed ones. As I started out by saying be wary of the var keyword - it's one sneaky bastard :)
The opinions expressed herein are my own personal opinions and do not represent
my employer's view in any way.