var is evil! - Peter's Software House

var is evil!

Yes I believe it is.

I was trying to read some code the other day and the developer had declared all his variables using 'var', and it wasn't java or javascript noooooo it was C#.  Now I know var is needed in certain cases, and should thus be used in those cases, but please, just because it is new and shiny do not use it everywhere!  Only use it when it makes sense. 

It is like the paper I was reading today that said if we implement a certain design pattern it will reduce the amount of memory an application is using.  Uh, since when does patterns manage memory?  Clearly the author has heard of this pattern and now thought it will solve all his problems, just like the MSDN blog I was reading that used var everywhere.

Use the right tools for the right jobs.

Published Wednesday, April 30, 2008 7:40 PM by Pieter
Filed under:

Comments

# re: var is evil!

I totally agree that var is evil! What bothers me more is that there is a Resharper warning that recommends replacing types with 'var'! When we upgrade to VS2008 and R# 4.0, I'm going to make sure that we turn that rule off!

Wednesday, April 30, 2008 9:21 PM by Trumpi

# re: var is evil!

Hmm, you haven't explained why you think it's evil though.

Thursday, May 01, 2008 12:54 AM by senkwe

# re: var is evil!

Hopefully most people will learn that var is nothing like the untyped declaration of VB scripting fame.

It think that it's pretty clear - only use var when the type of the variable you are declaring is unknown or anonymous (like when you create LINQ queries that return anonymous objects).

Friday, May 02, 2008 8:54 AM by tokes

# re: var is evil!

I have to disagree with hating "var" - on the face of it I didn't like var... but after having been working on a C# 3.5 project for the last 8 or so months I've come to appreciate it more and more...  I think if a var declaration is confusing it's only because of poor practices i.e. poor naming, or a method body being too large... both are bad code smells in their own right, regardless of whether your using explicit or implicit type declarations... in some ways it's cleaned my code up because it's made me more aware of these smells.

Having the ability to toggle between explicit and implicit in Resharper 4 EAP is nice too - if something is confusing then just right click and change it to an explicit declaration... a half second operation.

My 2ø worth :)

Wednesday, May 07, 2008 1:05 AM by Alex Henderson

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: