Using implicit typing [duplicate]
Asked Answered
H

3

8

Possible Duplicate:
Resharper: vars

Is there a reason that resharper suggests var thing1 = 5 as opposed to int thing1 = 5? It just seems that they mean the exact same thing except that var is harder/less comprehensible to a human reader. I would be curious to know if there is a difference in the way that the compiler interprets them, or if its just syntactic sugar.

Hagans answered 5/6, 2011 at 20:56 Comment(0)
T
7

No, the generated IL will be exactly the same.

I suspect if you take up Resharper's suggestion, it will also "suggest" going the other way - IIRC the default is to always offer the ability to change in either direction. You can change what it suggests within the options though.

Thyrse answered 5/6, 2011 at 21:0 Comment(1)
Wow, ReSharper is one mean troll. "Use var" -uses var- "No, no no, use int!" -uses int- "No, use var!"Filature
U
5

Usage of the 'var' keyword tends to be controversial. The 'authoritative' reference for this debate is http://blogs.msdn.com/b/ericlippert/archive/2011/04/20/uses-and-misuses-of-implicit-typing.aspx

Uriiah answered 5/6, 2011 at 21:1 Comment(0)
A
2

The reason that ReSharper is suggesting you use var is that it is by default configured to do so.

Go into the options for ReSharper, find the "Inspection Severity" settings under "Code Inspection", and a ways down into that list, find the setting labelled "Use 'var' keyword when possible".

ReSharper will, with the default setting of "Show as suggestion", by default suggest you use var instead of the actual type if:

  • You're constructing an object (ie. Type x = new Type(...);)
  • You're initializing it with a constant (ie. int x = 5;)

In both of these cases, ReSharper is programmed to assume that you can easily spot the correct type anyhow, so you can use var.

If you don't want that, change that setting. You can also change that setting directly in the dropdown you get from Alt+Enter, just pick the bottom item in the dropdown menu:

Alt+Enter dropdown menu

and it will pop open a dialog asking how to treat that setting:

Dialogbox

Also note that if you ask ReSharper to change the code to using var, it won't suggest you turn it back, but you can, by hitting Alt+Enter again and picking the option "Specify type explicitly".

Aguste answered 5/6, 2011 at 21:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.