3.2.08

C# 3.0 - var keyword

There's a new keyword on the block: var. And while many people are praising its wonderous benefits, I don't like it. Let's consider the facts:
  • It can only be used on variables initialized on the same line

  • It is statically typed when initialized, so strong typing is maintained
Visual Studio 2008 is smart enough to show you the inferred type when you go to use a var variable later, which is nice, but it doesn't solve the problem of code readability. There are plenty of articles with good examples of this, so I won't reiterate. However, today I came up with a new scenario that would provide some credibility to the use of var:
for (var i = 0; i < 400; i++)
{
if (i == 0)
Console.Write(i.GetType().Name);
}


Since the var i is in the range of 0 to 399, I hoped the compiler would realize that it could use a short (or even a ushort) when it typed it. It does not.

The reason is pretty simple, really. It's not intelligent. Since I assigned 0, which is by default an Int32, the variable i was statically typed as an Int32. If I change it to read var i = 0u, it will type it as a UInt32.

This isn't really surprising, but it's a little disappointing. My basic idea was that if the size of the loop changed (statically) in the future, I could save the trouble of changing the variable type manually. That is, if the compiler automatically picked the smallest variable type required.

In any case, I dislike the use of var immensely. I understand it is required for LINQ, but in any other case, it looks like pure laziness. One article I read said that typing "var" instead of "Dictionary" was savings. However, any software engineer will tell you the bottleneck is not in the typing, it's in the thinking. If I have to spend more time thinking the next time I look at this code to figure out what my new var type actually is, I've wasted time.

No comments: