Ever since var was announced as a keyword for C# 3.0, I have had issues with it.
I know that it is strongly typed, but something just felt wrong about it. It felt like some kind of an abomination.
Perhaps I just like to repeat myself = new Perhaps I just like to repeat myself.
Finally, I started using var, because I don’t know what the heck a LINQ query returns. I just know that if I put var at my variable declaration before my LINQ query, it just works. Then if I put var before my variable in my foreach loop, that just works too.
Reluctantly I started using var, but every time I did I would start to feel guilty. Like I did something wrong. Like I was a bad person. Like I was writing strongly typed VB code. I felt dirty.
Be clean my sons! Throw off your shackles!
I contemplated the issue for a good long while. It has been months that this var issue has been eating me, slowly leaking into my code. Then, I had an epiphany!
var is just an abstraction. I don’t need to know the type of variables as long as the compiler does.
There is no need to feel guilty when using var. It is preventing the reader of your code from focusing on the types of the variables and instead focusing on the purpose of the variables.
I rewrote some code using var wherever possible to see if it decreased readability at all. (I took it to the extreme)
public string reverse(string toReverse)
{
var reversed = "";
var lastCharacterIndex = toReverse.Length -1;
var firstCharacterIndex = 0;
for(var index = lastCharacterIndex; index >= firstCharacterIndex; index--)
{
var letter = toReverse[index];
reversed += letter;
}
return reversed;
}
Admittedly, it looks a little strange. But honestly, is it any more difficult to read than if I had put all the types in there instead of var? Does that actually give you any useful information that helps you understand this code? As long as my variable names are good, I would venture to say that the readability is improved, because anything that adds information that is not important to the code is a distraction.
Bonus: decoupling
As I was contemplating this issue, I realized something more than aesthetics pushed me to the var side of the force. var is reducing coupling in my code when I use it.
If I call a method that returns some object in my code, but I hold the reference to it with a variable I declared using var, if that method changes to return something else with similar usage, I won’t have to change the source code. (I will have to recompile though.) In many instances var can serve as a bonus to slightly decouple your application in places where methods return concrete types. Every little bit helps.
Anything that reduces your dependency on concrete types, and makes your code more flexible while still catching issues at compile time instead of runtime, is good in my book.
Hinging on the IDE
There is one caveat here. This all depends on the IDE. You have to have intellisense and auto-complete, otherwise this whole thing falls apart. I don’t need to know the underlying type, because I can just hit “.” on my keyboard and Visual Studio tells me what my options are. I can go back and figure out what the type is by just hovering over the var declaration in Visual Studio.
Without those abilities, var would not be as good. Without those capabilities you would have to go back to where the variable was declared, and possibly trace up a method call to figure out the return type to know what type the var variable will be initialized to.




[...] Do You Have a Case of var Guilt? – John Sonmez talks about the guilt he first felt when using the var keyword in C#, and shares how his feelings changed as he realised that var, as well as being shorter to type, actually helped reduce his dependency on concrete types therefore affording some looser coupling in his applications [...]
By: The Morning Brew - Chris Alcock » The Morning Brew #595 on May 7, 2010
at 1:32 am
So, why not:
01 public string reverse(string toReverse)
02 {
03 reversed = “”;
04 lastCharacterIndex = toReverse.Length -1;
05 firstCharacterIndex = 0;
06 for(index = lastCharacterIndex; index >= firstCharacterIndex; index–)
07 {
08 letter = toReverse[index];
09 reversed += letter;
10 }
11
12 return reversed;
13 }
By: Tim on May 7, 2010
at 1:49 am
Did you just javascript rick roll me? Actually it is pretty interesting to look at it that way without even having the vars. Is the value in immediately knowing on a line if a variable is being delared or not? I’m not sure.
By: jsonmez on May 7, 2010
at 5:57 am
Nice. I can relate to feeling this way at first too. Now it’s time to change your ‘Email Me’ section to use var for your stringbuilder reference!
By: Bruce Lindsay on May 7, 2010
at 11:05 am
Good call! Done!
By: jsonmez on May 7, 2010
at 11:13 am
There’s no repetition in:
int lastCharIndex = toReverse.Lenght – 1
as opposed to:
Dictionary<int, Dictionary> lookup = new Dictionary<int, Dictionary>();
I’d rather use var in the 2nd case where initialization and declaration match. In the 1st case, the type might not always be evident without using the mouse – like in this example:
var table = GetBindingsTable();
And a second concern about the loose coupling: are you not afraid that one day you’ll get the wrong type because somebody else change a method and the compiler will not warn you just because it happens to have the same public API? I’m afraid that this could introduce subtle bugs…
By: Dejan Radovic on May 10, 2010
at 9:20 am
Good point, I still wonder in the first case do you actually need to know the type? You really just need to know the methods available on the type. Think about how we use interfaces. The same would apply about someone changing the type.
By: jsonmez on May 10, 2010
at 9:39 am
Ok, wild…. even the code definition window will work with the var keyword… bizzzzzarre!
I typically like to click the variable, hit F12, then click the type, and hit Ctl+\+d (control backslash d) to show the type def (frequently from metadata) in the Code Definition Window… or just F12 again.
But I was shocked when I changed Uri to var, hit Ctl+Sh+b (compile) and then hovered over the var … hit Ctl+\+d and there was Uri (from metadata) in the Code Definition Window… what a shocker.
I’m so confused! this seems just wrong from a best-practice standpoint, but totally Rock-N-Roll from the standpoint of how crappy JavaScript is regarding F12. It almost reels C# into VB territory… perhaps we’ll see something interesting now for C# like in VB now with COM interop…. perhaps I’m missing it and this IS it.
Dan “Stoic Strong Type’r” Wygant
By: Dan Wygant on May 13, 2010
at 12:55 am
For me your caveat says it all. The need for the ide to be able to supply you with the type information is a clear indicator that you need to know the type information. I feel that if you cannot read/write the code without the ide you did something wrong. Don’t get me wrong, I love the ide, I love the productivity gain, but I also love being able to use my skills even with inferior tooling. Personally I’m in agreement with Dejan, using var when the initialization clearly shows you what type your using is fine, but using var for every declaration does in my opinion makes your code harder to read because you have to backtrack to discover what types are in play.
By: Andreas Jydebjerg on May 19, 2010
at 1:08 am
“Perhaps I just like to repeat myself = new Perhaps I just like to repeat myself.”
Actually made me laugh out loud! thankfully no one is around. Great post!
By: Tion on June 24, 2010
at 4:05 pm