Var is Bad

Wednesday, May 26 2010 - ,

Var is Bad

C# 3.0 added LINQ, which is a great feature for working with data. Okay, so maybe Entity Framework is going to make it obsolete (depending on who you ask), but it still served a great purpose for a little while. However, to facilitate LINQ, Microsoft also introduced the bane of good programming – var. Var is a way to implicitly create variables of a type. The compiler figures out what the type is based on what you first assign to it. So in this case:

var a = “Hello, World!”;

“a” will be of type String. And in this case:

var b = new SqlCommand();

“b” will be of type SqlCommand. What’s wrong with this, you ask? Isn’t it great because it leads to less typing? Yes, it is less typing, but that doesn’t make it a good thing. Take a look at this little example:

var value1 = “Hello”;
// Several lines of code
var value2 = value1;

What type is value2? A string. Pretty simple, right? Yes, as long as value2 is in close proximity to value1. Just imagine that value1 is defined at the very top of a very complex algorithm, and value2 is not defined until the very bottom, potentially several screens of code away. An extreme case, yes, but it does happen. Visual Studio can tell you what the type is if you hover over it, sure, but what happens when someone is trying to do a code review, not in Visual Studio? That person now has to go scanning through the prior code to figure out what the type of that variable is. Is it really that difficult to type "string value2" instead of "var value2"? No, it is not.

Var is a crutch. It is there for lazy developers. And it is really annoying because it seems like every person that blogs about C# uses it almost exclusively now in all of their code examples. Just look at any post on Scott Hanselman’s blog to see what I mean. Just because you can do something with your favorite programming language, it doesn’t mean you should. I can use “goto” in C# too, but you’re never going to catch me doing it. Var is the same sort of thing – a feature that has very limited required usage, so let’s keep it that way and only use it when required, not all over the place.

UPDATE: Even Microsoft agrees that var should only be used when required - maybe they should tell their community mouthpieces that.

Similar Posts

blog comments powered by Disqus