var vs explicit declaration

c#

Solution

In terms of execution time efficiency, it makes no difference. It is indeed compiled into exactly the same IL. The variable will still be statically typed, it's just that the type is inferred from the initialization expression.

"Inferred" means "worked out from other information". So if the declaration is:

string x = "hello";

the variable `x` is explicitly declared to be of type `string`. The compiler doesn't have to work anything out. If you use `var`:

var x = "hello";

then the compiler finds the compile-time type of the expression being assigned, and makes that the type of the variable. `x` is still known to be a string variable everywhere else in the code.

If the developers you're working with think that `var` behaves dynamically, I would be very cautious about other information they tell you. You might want to discreetly suggest that they learn a bit more about how new language features work before judging them.

In terms of developer efficiency, that's a much harder question to judge. Personally I use `var` quite a bit - particularly in tests - but not everywhere.

Problem

Possible Duplicate: Use of var keyword in C# Hi, Just moved job and I am used to using `var` a lot. At my previous job we were doing lots of TDD and using resharper. In this job they hate third party tools and the developers here say that it is not good to use `var` all the time and it is not as efficient as explicit typing. Some time ago I thought the same but now I have gotten so used to it, and it makes my code look neater. I have read some posts and there seems to be confusion whether it is as efficient or not. I read that using `var` produces the same IL code. So should it not be as efficient? Somewhere else I read that even though using `var` produces the same IL code it has to find out what type it is. So what does 'inferred' really mean then? Some clarification as to whether performance wise they are the same would be fantastic.

Original source

Related problems