Use of c# var – Lazy or Flexible?
Posted by edc73 on July 25, 2008
A code review today raised concerns about the use of var such as:
var results = new List<LabResultSummary>();
as opposed to
List<LabResultSummary> results = new List<LabResultSummary>();
Specifically, the question was “Why is type inference needed or even useful in the below? I gotta say, it smells of a lazy developer to me.
“
And then my response:
—————————————————————–
My first inclination to “var” was similar to yours, but I’ve converted.
1. For small methods (which all methods “should” be), what the variable is is obvious from how it’s instantiated (You can only use var when it’s instantiated in the same statement as it’s declaration)
2. It’s still strongly typed (it’s not a vb6 dim object/variant)
3. You can only use on private method variables, so no “leakage” of intent.
4. And damn, when I’m writing a lot of code that’s in flux, it’s saved me lots of work to just change the variable type. For example, refactor a method to return the interface instead of the concrete type. I don’t have to go and touch every single variable that ever called that function.
There’s probably others, but that’s off the top of my head. Again, when I first read about them, I got the “smell” too. But decided to give it a shot and have become a fan. Makes my coding agile
————————————————————
Thoughts?

jayray said
So I start with: unless there is a good reason, declare your variables using the correct interface. So is there a good reason not to?
So there are two different cases discussed here – on a private variable and on a public interface.
On the public.. just do it. Yes, it can result in “sweeping” changes, but you want interfaces to be explicit. If you change what you are returning, your consumer typically is going to need to change anyway. So declaring abstractly is probably not going to buy you anything.
On the private.. the first couple of responses don’t give a reason that it is a better to declare as var, but rather try to say its not that bad. Unless there is a good reason not too, just do it. Its not that hard.