On the potential abuse of the var keyword

1 minutes read

Originally posted on: http://geekswithblogs.net/jolson/archive/2008/12/14/on-the-potential-abuse-of-the-var-keyword.aspx

This question/conversation has come up quite often when chatting with friends and other developers. With the introduction of the "var" keyword in C# now, when should it be used (and, perhaps more importantly, when should it not be used). Here is a quick summary on my thoughts...

My personal feeling is that it's a problem if I have to rely on Intellisense in order to be able to tell what type a variable is when it is declared. It's important to keep the future audience in mind while you are writing code (this could be future developers needing to maintain your code, or even yourself years down the road). After all, writing code is the easy part. Reading it (and hence, reverse engineering it to a degree) is the hard part.

So, when you write code that requires another developer to use Intellisense (or go poking around other pieces of code that may be contextual irrelevant) to understand a piece of code, I would contend that you are not writing good code.

This brings us to the var keyword. Good usage? Using it to automatically infer variable types on declaration/instantiation lines of code:

var people = new List<People>();
var lookup = new Dictionary<string, SomeType>();

However, I really don't like when developers use the var keyword on a variable declaration based on the return of a method call. Without Intellisense, how am I supposed to be able to tell what type the variable is?

// This is *bad*, don't do this
var local = SomeMethod(...);

How about loop variables? My personal take (though I could go either way) is to not use the var keyword on loops:

// I prefer this
for (int i = 0; i < 10; i++)
{
...
}

// over this
for (var i = 0; i < 10; i++)
{
...
}

In general, I think it is important not to be a lazy coder and do something just because it makes it easier on you at the time. As a developer, you need to think about those that will come after you and maintain your code. Don't make it any harder on them than it needs to be. Their jobs are already hard enough.

What are your thoughts? Where do you use the var keyword? Where do you NOT use the var keyword?

Updated:

Leave a Comment