Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Var is Bad

0.00/5 (No votes)
7 Jun 2010 1  
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:

C#
var a = "Hello, World!";

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

C#
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:

C#
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here