C# 'var' keyword versus explicitly defined variables [duplicate]

一曲冷凌霜 提交于 2019-11-26 20:21:49

问题


This question already has an answer here:

  • Use of var keyword in C# 86 answers

I'm currently using ReSharper's 30-day trial, and so far I've been impressed with the suggestions it makes. One suggestion puzzles me, however.

When I explicitly define a variable, such as:

List<String> lstString = new List<String>();

ReSharped adds a little squiggly green line and tells me to:

Use implicitly type local variable declaration.

If I then follow its suggestion, ReSharper changes the line of code to:

var lstString = new List<String>();

So, is there some sort of performance gain to be had from changing the List<String> to a var, or is this merely a peculiarity of ReSharper? I've always been taught that explicitly defining a variable, rather than using a dynamic, is more optimal.


回答1:


So, is there some sort of performance gain to be had from changing the List to a var

No but this is not the only valid reason for a refactoring. More importantly, it removes redundance and makes the code shorter without any loss in clarity.

I've always been taught that explicitly defining a variable, rather than using a dynamic, is more optimal.

You misunderstand what var means. This is not in any way dynamic, since it produces the same output. It just means that the compiler figures the type for the variable out by itself. It's obviously capable of doing so, since this is the same mechanism used to test for type safety and correctness.

It also removes a completely useless code duplication. For simple types, this might not be much. But consider:

SomeNamespace.AndSomeVeryLongTypeName foo = new SomeNamespace.AndSomeVeryLongTypeName();

Clearly, in this case doubling the name is not just unnecessary but actually harmful.




回答2:


Nope. They emit the exact same IL.

It's just a matter of style.

var has the benefit that makes it easier for you to change the return type of functions without altering other parts of source code. For example change the return type from IEnumerable<T> to List<T>. However, it might make it easier to introduce bugs.




回答3:


The var keyword does not actually declare a variable with a dynamic type. The variable is still statically typed, it just infers the type from the context.

Its a nice shortcut when you have a long typename (generic typenames can be long)




回答4:


Less typing = more productivity :)



来源:https://stackoverflow.com/questions/429446/c-sharp-var-keyword-versus-explicitly-defined-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!