How Var Will You Go?

A snippet of code I saw posted on a forum today goes a long way toward explaining what I don’t like about the var keyword in C#:

var something = new Size(double.PositiveInfinity, double.PositiveInfinity);

The writer was simply trying to illustrate a point about calling Measure() on a newly-constructed element in Silverlight. What, you might wonder, is wrong with that code? Well, syntactically nothing is wrong with it. The var keyword is a placeholder, and the compiler will look at this statement and figure out that the type of ‘something’ is typeof(Size). The problem? Any programmer who comes along later and has to read and maintain this code now has to perform the same exercise as the compiler: see ‘var’ keyword; parse RHS of statement; figure out type; nod head wearily and continue.

Why? For no reason at all. There was no benefit to using var in this scenario. It simply saved the writer from typing one additional letter:

Size something = new Size (double.PositiveInfinity, double.PositiveInfinity);

And that, ladies and gentlemen, is why I don’t like seeing the rules relaxed just so we can have neato stuff like LINQ. Maybe I’m a hoary old luddite, but I use strongly-typed languages for a reason: namely that they are better. Once you relax the rules humans will take advantage, and who can blame them? It’s a burden to type that extra letter, and obviously in the .NET framework there are a metric ton of examples where the advantage of three-letter var is much greater:

var args = new DependencyPropertyChangedEventArgs();

Now that’s some keystrokes saved right there. Who could blame me? It’s not a huge problem when the type is right there next to the operator, but what about when the type is embedded in a method return?

var args = SomeMethod();

Well, that’s a little harder to figure out, isn’t it? Thank God we have Intellisense to show us what the return type of that method is.

Leave a Reply

Your email address will not be published. Required fields are marked *