Wednesday, March 5, 2008

Implicitly-typed variables in Resharper 4.0

By now, most of us already know that Linq is everywhere, and therefore, also are anonymous types. To make anonymous types usable with Linq, implicitly-typed variables are required.

The "var" keyword tells the compiler to infer the type from what's on the right-side of the attribution. C# is a statically-typed language, and the “var” keyword doesn't change this.

When you compile the code into IL, you'll see the type explicitly used there. So what's the harm of using "var" all over the place?

Before jumping to the answer right away, I would like to refer you to Steve McConnell's Code Complete, where he reminds us that one should strive to write code that's easy to read. it sure is nice when code is both easy to write and read (like the newly added "automatic properties" C# 3.0 feature). But readability always prevails.

So, to answer my question about the harm of using "var" everywhere, I would say that it can be really harmful to readability.

Sure, if a variable declaration is like the following, there's no problem in using "var":


var baby = new Person();


It is obvious that the variable baby is of type Person. But imagine some method, badly named GetNewOne, returning a new Person object.


var baby = GetNewOne();


How in the world would you know that baby is of type Person? I know if you're using Visual Studio, you can simple hover the mouse over it. But I think I shouldn't rely on a tool to provide me with code readability.

In the example above I definitely want my code to be like this:


Person baby = GetNewOne(); //TODO: Refactor this method name please!!!

I've been playing with ReSharper 4.0 nightly builds on Visual Studio 2008 targeting .Net 3.5, and interestingly enough, every time you use something like "Person baby = GetNewOne()", ReSharper 4.0 will put a squiggly line small green line (hint) under Person, suggesting I should use the "var" keyword instead. See below.



ReSharper 4.0 is not out yet, and maybe (hopefully) this code suggestion will not be in the final version, but I thought it was interesting and wanted to share.

2 comments:

Ilya Ryzhenkov said...

Do you really have squiggle on line like this:

Person baby = GetNewOne();

It should be just hint (small green line).

Gustavo C said...

Ilya, you are correct. I made a mistake when I said Resharper would place a squiggle. It really puts a green line.
I changed the blog post.
But what's the difference between a squiggle and a hint? Aren't both of them suggesting this code change?
Thanks for your correction and for your hard work on Resharper. It is a wonderful tool.