I recently attending a meeting of the Fairfield / Westchester .NET User Group, in which Richard Hale Shaw presented on LINQ and C# 3.5 features. During the presentation there was a brief but spirited debate over the use of the var keyword in C#. Specifically, at issue was using var without anonymous types.

Richard, who gave an excellent presentation, took the “for” side. He argued in favor of the more terse variable declaration syntax provided by var. On this point I agree. If the compiler is able to infer the declared type from its assignment (new or method return type), then why not save some keystrokes by replacing the former with the latter?

KeyValuePair<string, string> items = new KeyValuePair<string, string>();
var items = new KeyValuePair<string, string>();

The “against” crowd objected to the dynamic feel of the var keyword. It was argued that code clarity is sacrificed for this lack of verbosity. It’s easy to know the type of items in the first line of code above. The second line is still pretty clear. But there’s another case…

var items = someObject.SomeMethodReturningAKeyValuePair();

If a developer isn’t familiar with the return type of SomeMethodReturningAKeyValuePair, then Visual Studio has to provide this information (mouse over, Intellisense). Personally, I think spending time with any language that supports duck typing gets one over this concern rather quickly…

Personally, I would prefer there not be a var keyword. Don’t get me wrong, I’m a fan of anonymous types. It’s just that var seems unnecessary. As an alternative approach consider Python and Boo.

Python is a scripting language and as such is not statically typed. It clearly makes sense for Python not to require a declaring type. But Boo, which is statically typed, will compile the code below just as easily as Python will interpret it.

d = Duck()

Neither Boo nor Python require those three contentious characters, OK four counting the space. So why does C#? If it’s a matter of scope, Python has a solution:

a = "foobar"

def foo():
    a = "bar"

def bar():
    global a
    a = "foo"

print a
foo()
print a
bar()
print a

The snippet above will print the lines below. The global keyword is used to tell the interpreter that a global variable is being changed. Without it, Python will create a new locally scoped variable.

foobar
foobar
foo