0

We use Resharper with visual studio. I have the following code

 CMS.PortalEngine.PageInfo pageInfo = CMSContext.CurrentPageInfo;

However, Resharper is suggesting me to change to

 var pageInfo = CMSContext.CurrentPageInfo;

why is that? I thought by declaring pageInfo var, isn't the compiler going to bind it to the actual type at RunTime? How is that more efficient?

Please share your thoughts on this

doglin
  • 1,651
  • 4
  • 28
  • 38

1 Answers1

0

The use of var has no bearing on the compiled code or it's efficiency. It is sometimes mandatory - when dealing with anonymous types - but used incorrectly it won't compile. If it does compile, it will result in the same code as it if you had explicitly used the type of the expression on the RHS of the assignment.

Occasionally, you may want to explicitly specify an interface or super-type on the LHS of an assignment and leverage an implicit cast. This has no clean equivalent with the use of var. e.g.

/* Given these classes */
class Animal {}
class Dog : Animal {}

/* This has no simple var equivalent */
Animal animal = new Dog();

/* Since this would make animal of type Dog */
var animal = new Dog();

/* But you can do this - don't why you'd want to though */
var animal = (Animal)new Dog();

For the most part, use of var is merely a matter of style.

In Resharper, you can decide how opportunities to use var are indicated - look in Settings>Code Insepction>Inspection Severity where two entries pertain to var:

  • Use 'var' keyword when initializes explicitly declares type (defaults as a Suggestion)
  • Use 'var' keyword when possible (defaults as a Hint)

You can change these as you like.

James World
  • 29,019
  • 9
  • 86
  • 120
  • but let's say , you use "var" , it is implicitly cast, as supposed to explicitly cast. So when in run time, after the compiler runs, you still have to type cast it in the run time. I believe that is what is going on. Please feel free to correct me if I am wrong – doglin Oct 24 '13 at 14:44
  • 1
    You are wrong. var does nothing at runtime. It is a keyword that the compiler reads and then deduces the intended type. It *only* has compile-time semantics. See http://stackoverflow.com/questions/3632918/var-keyword-runtime-or-compile-time – James World Oct 24 '13 at 14:48