2

Possible Duplicate:
Use of var keyword in C#

I use resharper in Visual Studio. Every time when I create class instance resharper suggest me to use var instead of exact type of class. Why using var operator more appropriate?

Community
  • 1
  • 1
Polaris
  • 3,643
  • 10
  • 50
  • 61

2 Answers2

6

ReSharper is suggesting you to use var via a context action.

A context action in ReSharper (commonly designated by a pencil icon), much like an intention action in IntelliJ IDEA, is something that you can use if you like to, but it's not in any way obligatory. This is opposed to a quick-fix (a yellow or red bulb) that is specifically targeted to fix a code issue that ReSharper has discovered.

Time and again ReSharper users get stunned when they see ReSharper suggesting using var, then (as soon as you've accepted the suggestion) suggesting using explicit type specifier again. But considering the nature of context actions, it's completely fine to have pairs of opposite context actions like this, and ReSharper has plenty of them.

If you don't want ReSharper to display this particular context action, you can turn it off in ReSharper > Options > [Language] > Context actions

Jura Gorohovsky
  • 9,886
  • 40
  • 46
  • Btw, using or not using var in different scenarios is something that you can enforce in batch mode using ReSharper's Code Cleanup. – Jura Gorohovsky Sep 26 '10 at 10:51
  • Create a custom code cleanup profile, set "Local variable declaration style" to "Use 'var' only when initializer has type usage", and apply the profile to a custom selection. See details at http://www.jetbrains.com/resharper/webhelp/Code_Cleanup__Creating_Custom_Profiles.html – Jura Gorohovsky Sep 26 '10 at 10:52
0

Less repetition, for starters. Which one do you like more:

IDictionary<string, object> foo = new SortedDictionary<string, object>();

or

var foo = new SortedDictionary<string, object>();

Personally, I find the latter much more readable.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435