views:

143

answers:

3

Possible Duplicate:
Use of var keyword in C#

I use it almost all the time unless I'm not assigning to the variable immediately, in which case it's not an option. Good or bad?

+1  A: 

Used implicitly typed variables (var keyword) is:

  • Great: when you need an anonymous type.
  • Good: when the type is obvious (var sb = new stringbuilder();)
  • Bad: when the type is not so obvious (var doc = repo.getdocs("base");)

If you find yourself using if often, that's probably fine. Using it all the time means that sometimes people are going to have to investigate to see what type you're using. It should be clear looking at printout what type is being used.

Patrick Karcher
But ... one can just hover the mouse over `getdocs` function ... we, as Python hacker I like var a lot.
Hamish Grubijan
But at the same time, people shouldn't have to work. It's a balance. I myself use implicit typing a lot. (I'll be getting into Python this summer. Can't wait!)
Patrick Karcher
Hovering is a pain and doesn't work when you're outside the IDE. I'd much rather just see the type explicitly declared. Is it that hard to type it out? Some people are too lazy.
senfo
A: 

You have to find your own balance between ease of writing and ease of reading. Granted, you can hover over the next use of the variable to see the inferred type, but if you're not reading the code in the IDE, that might be an issue.

One edge case that I recently encountered was that I was trying to manually replace particular instances of Foo in my project with instances of Bar (an improved Foo). I would do a Find All for Foo, and it turned out that I missed a few because I had done var quux = GetSomething() where GetSomething returns an instance of Foo. But, that's a bit of an edge case, and I wouldn't put too much weight on that alone in regards to using var.

Mark Rushakoff
A: 

This is apparently the recommended way to go (if you use tool like Resharper, it will by default suggest to replace specific type by 'var' wherever possible). I personally prefer using specific types for readability. However, if the code is good quality and methods are normal length, it remains readable even with 'var' used. There is a lengthy discussion on the subject here: http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c

Otherwise, there is no performance impact of using var (it's not like using 'object' and type casting).

Francis