Geeks With Blogs



Add to Technorati Favorites

An Archived Managed World This blog has moved to

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?

Posted on Sunday, December 14, 2008 12:56 PM C# Dev Center , Development | Back to top

Comments on this post: On the potential abuse of the var keyword

# re: On the potential abuse of the var keyword
Requesting Gravatar...
I agree with you - abuse of var can obfuscate the code. In addition to the examples of use listed here, I prefer to use var in conjunction with linq expressions, as the return types of those can be quite elaborate sometimes without really contributing much to more readable code (IEnumerable<IGropuing<...>>), and because it should be possible to deduct the appropriate return type from the select clause of the query. And, of course, in conjunction with anonymous types, it would be natural to use var (don't use them alot, though, as they also posess quite some obfuscation potential).
Left by steinjak on Dec 15, 2008 4:50 AM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
I don't think the 'bad' example is so clear-cut. There is no less information in:

var foo = SomeMethod()

than you'll get from common idioms like method chaining:


or nested method calls:


In both of those examples, we call and use the result of SomeMethod() without explicitly declaring its type.

There are also cases like:

var controller = CreateController()

which seem pretty harmless.

I don't think hard rules really work for this one. Of course, the Framework Design Guidelines may disagree with me :)
Left by Nicholas Blumhardt on Dec 15, 2008 8:20 AM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
Steinjak, excellent point on LINQ! I use it there as well but had forgotten about it.
Left by Jason Olson on Dec 15, 2008 10:08 AM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
Steinjak, excellent point on LINQ! I use it there as well but had forgotten about it.
Left by Jason Olson on Dec 15, 2008 10:09 AM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
Nick, I agree that it definitely isn't black-and-white and that there is some gray area.

I actually don't like nexted method calls either for the same reasons. However, chaining is a different manner. Usually, with chaining methods (w.r.t. fluent interfaces), the intermediate types are not necessary to be known because the intention of the code is obvious because of the English-like reading of the fluent interface.

I agree with you on the point of "var controller = CreateController()". When it's that obvious, I don't have a problem with it because the code is still readable. Another example of where this pattern exhibits itself is in libraries like NHibernate:

var sessionFactory = configuration.BuildSessionFactory();

But in both cases, the method being called is named specifically like a Factory method. So from the naming alone, it is just obvious enough to not need to rely on Intellisense to understand what is going on.
Left by Jason Olson on Dec 15, 2008 10:15 AM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
I disagree completely. var is compiler cruft and the type "telegraphing" (if you will) encourages lazy developers to continue to be lazy. frankly, I don't care if you do this

for(int i =0...


for(var i=0...

because I can clearly see the intent of the developer based on the right side of the operator. Same goes when coming off of a method, IF the method's intent is clearly indicated by the method name. If it's not, then you've got a poorly named method, which is a code smell and should be refactored. For some reason C# is in love with the notion of declaring types for variables siting type safety as the reason but we all know that isn't the same as type safety. In my experience all it does is simply add cruft that gets in my way. Take the following for example:

Duck item = GenerateADuckForMe();

var item = GenerateADuckForMe();

item = GenerateADuckForMe();

Are NOT equally articulate. But depending on who you ask you'll get a different answer for which is the most elegant and articulate. You, I assume, would prefer the first while I, on the other hand, would rather the last. I'll rely on the method to generate a duck for me in any way it sees fit and I'll deal with it then. Unless our = operator becomes a pattern matcher like in Erlang, it's superfluous.

So, to answer your question in short form: I disagree. If people articulate their code, the right side of the operator will clearly indicate the intention of the left side. Other languages do it all the time (F#, Boo - both strong typed) and I wish that C# would wise up and do it as well.
Left by Leon on Dec 31, 2008 7:44 PM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
Nope, I agree with you completely. I would actually prefer the last one you said, if working in a language where it is possible and preferred/encouraged (like Boo/Ruby/etc.).

And I agree that if the method is named properly (especially in the case of a factory method like you have here), I have no problems with the usage of var to remove the ceremony from what code does need to be written. It's when the code isn't written well (unfortunately all too common), that I don't like the usage of var. Basically, it boils down to developers writing code where the IDE (Intellisense/Tool-Tips/etc.) are required to easily read/understand the code. That's bad, and no developer who is passionate about their craft should be writing code like that.

All in all, I think C# (or many CLR-based languages in general) have way too much ceremony I have to express directly in code that merely gets in the way of me expressing the solution to the problem I'm trying to solve. However, working within the context of that language, I think you have to "resign" yourself to the constraints you are given and operate well within those constraints. Even the "." operator and "()" around method calls is extra ceremony that perhaps isn't necessary. The presence of those two things certainly makes expressing solutions a bit more limited (especially considering the power of internal DSLs you can express in languages like Ruby).

However, you make an _excellent_ post that I just started thinking about the other day. There's nothing written in stone that says a statically-typed language has to be filled with unnecessary ceremony. Like you state, F# is a good example of a language that removes ceremony from the language while remaining heavily statically-typed.

When it comes to writing OOP code, I'm one of the first ones to admit how much I hate ceremony and how much I would prefer to be writing the code in a dynamic language like Smalltalk/Ruby/Python/etc.
Left by Jason Olson on Jan 01, 2009 1:18 AM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
The new var feature IMO is just another way to shoot yourself in the foot. I never use it - period, it reminds me of the Variant union type in COM which in my opinion is bad coding practice defined. In my opinion - loosely typed things like var or variant are bad news, period. Even in my Linq queries, I still explicitly declare the type my query is going to return, I know I am working with a collection of widgets of a given type - and I know it will not change. If i need to use a base class to enable polymorphism then that is the path I always choose. I am just a big fan of strongly typed things, it makes my code much easier to read and makes it a lot easier to keep the bugs out.
Left by Chase Thomas on Jan 23, 2009 7:07 AM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
Chase, to clarify, var is in no way loosely typed. It is, in fact, very strongly typed just as if you typed the type's name (it has nothing in common with Variant outside of similarites in its name).

All "var" does is to tell the compiler "infer this type for me", but variable still has a strong type and can't change that type again.
Left by Jason Olson on Jan 23, 2009 9:57 AM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
When it comes to writing code, there are only two rules that I abide by (even at the cost of efficiency):

1. The code must work
2. The code must be maintainable

I've worked on way too many projects where I had to make a systemic change to code where the original author worshiped at the altar of abstraction. Talk about a nightmare, and the var construct doesn't make it any less confusing.

To that end, I'm on board with Chase Thomas - I don't think I'm going to ever make use of the "var" construct on principle.
Left by Adam McKee on Feb 10, 2009 12:56 PM

# re: On the potential abuse of the var keyword
Requesting Gravatar...
I use the `var` keyword whenever possible.

Code should be written in such a way that explicit local variable types are not necessary. When you encounter a local variable, its type should either be clear from the context, or not matter to you.

var file = entry.PackageFile;
var package = new Package(file);

`file` might be a string, a FileInfo, an actual Stream, or even a TextReader. But it doesen't really matter. It represents a file. Period. The exact type is an implementation detail only relevant to the two participating methods and the compiler.

I, however, agree that `var` makes a program more difficult to read when you have no access to a smart IDE. `var` with IntelliSense is as good as static types.
Left by SealedSun on Mar 11, 2009 12:33 PM

Your comment:
 (will show your gravatar)

Copyright © Jason Olson | Powered by: