which one is better or maybe faster for declaring a variable?
var ds = new Class1();
OR
Class1 ds = new Class1();
I myself believe that second one should be faster coz compiler doesn’t need to look for the type Class1, but some addins like ReSharper always notify me to change Class1 to var.
Can anyone explain me why?
They compile to the same IL, so neither will be faster. However, there can be a big difference in readability.
I tend to favour explicitly declaring the type of the variable, but use
varif any of the following cases applies:As with many issues of readability, there’s a vast range of opinions about where to use
var– from “nowhere” to “everywhere”. Note that you can change what ReSharper recommends for you in the options. (I seem to remember that by default it “recommends” both ways round – so really it’s just making it easier for you to switch.)A couple of answers have mentioned the number of keystrokes involved. I think this is the worst possible reason to favour
var. I’m rarely, if ever, bottlenecked on typing speed. My coding speed is far more heavily dependent on my understanding of the problem domain, and on how clearly I can imagine the solution. I would far rather enter 2000 keystrokes but end up with an elegant design which is actually represented in 100 characters than type a mere 500 keystrokes for a less-readable 500-character design. Think about the time spent reading the code rather than the mechanics of typing.