var vs explicit declaration
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.
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.
var
is converted to is exact type during compilation
.no problem in efficiency as per my knowledge.
IL for this code is shown below:
class Foo
{
void Bar()
{
var iCount = 0;
int iCoount1 = 0;
}
}
链接地址: http://www.djcxy.com/p/53806.html
上一篇: C#3.0中var关键字的优点
下一篇: var vs显式声明