tags:

views:

111

answers:

4

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?

+1  A: 

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.

Chris Jester-Young
Yes, when using constructors. But var foo = SomeFunction(someparameter); is not very readable. I like the previous much better.
Andreas Paulsson
+2  A: 

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

gorohoroh
Btw, using or not using var in different scenarios is something that you can enforce in batch mode using ReSharper's Code Cleanup.
gorohoroh
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
gorohoroh