“var” is a pronoun
One of the great features of C# 3.0 is the new “var” keyword. It allows the type of your local variables to be inferred and thus saves you from too much typing (no pun intended).
For example, instead of having to type:
MyClassWithAnIncredblyLongName foo = new MyClassWithAnIncredblyLongName();
You can type:
var foo = new MyClassWithAnIncredblyLongName();
However, this convenience can be taken too far. When I first started using C# 3.0 I got all enthusiastic about using var, but it didn’t take me long to recognize the pitfalls. It’s fine to use “var” as in the example above, but what about this:
var guyToHandle = GetTheGuy(someVariable);
So what type is guyToHandle? Sure you can move the mouse over “var” in Visual Studio and the tool tip will tell you, but wouldn’t it be easier to read and therefore maintain if it said:
Employee guyToHandle = GetTheGuy(someVariable);
Now with just a quick look you can see what the type is. No mouse required.
The equivalent in the English language to “var”is a pronoun and similar problems can occur when a pronoun is misused:
Joe and Bill were talking and he said “blah, blah, blah”. Which “he” is it? Hence the title of this post.
As with any language feature, “var” is a tool to use for the appropriate job. So use it wisely.