13 November 2008

Implicitly unreadable: the C# “var” keyword and lazy code

The introduction of implicitly-typed local variables was originally intended to support anonymous types in C#. Introducing the var keyword made sense in this context – after all, anonymous types don’t have names that you can declare. The problem is that implicit typing can be applied to declarations of regular types and even fundamental types. If you really want, you never have to explicitly type a local variable again.

I know that “var” doesn’t mean “variant”, I know that variables declared using the var keyword will still be statically typed and I know that the intellisense in Visual Studio will still work for them. However, I am starting to increasingly see code samples that make heavy use of var and the impact of readability can be pretty extreme – it really is the kind of thing that makes a war-weary old coder like me shiver.

Jeff Atwood has advocated using the var keyword “whenever and wherever it makes your code more concise” even recommending it as appropriate for fundamental types. His main justification is over reducing the amount of redundant code. For example, a statement such as:

StringBuilder myVariable = new StringBuilder();

Can be re-written as

var myVariable = new StringBuilder();

There’s no doubt about the type of myVariable, you just have a more concise code statement. Although I understand the desire to write more concise code, it would make more sense to eliminate this redundancy by removing the type declaration from the right-hand side of the statement, i.e.

StringBuilder myVariable = new();

Redundancy aside, the main problem for me is that you can use implicit typing to produce code like this:

var myVariable = System.IO.File.Open("test.txt", FileMode.Create);

This does produce a FileStream object, but you wouldn’t know it by looking at the code. It may compile okay, but it’s pretty unhelpful for other developers.

Short cuts can improve productivity and having to write less code can be considered a positive step, but not if it undermines the readability of code for other developers. For my money, using implicit outside of anonymous types is a license to write lazy code.

var n = new int[] { 1, 2, 3 };

Filed under C#, Net Framework.