Pros & Cons of var datatype in .net 3.5 [duplicate]

我的未来我决定 提交于 2019-12-08 09:08:37

问题


Possible Duplicates:
Use of var keyword in C#
Use of “var” type in variable declaration

Hello everybody,

"Var keywork it require explicitly type casting Avoid boxing and unboxing value types where possible."

Is it advisable to use var keyword instead of explicit datatype?


回答1:


From ReSharper Horizons blog:

  1. It induces better naming for local variables. When you read local variable declaration with explicit type, you have more information at that moment and something like "IUnitTestElement current" makes sense. However, when this local variable is used later, you read "current" which takes some time to figure out the meaning. Using "var currentElement" makes it easier to read at any place.

  2. It induces better API. When you let compiler deduce type from method return type or property type, you have to have good types in the first place. When you don't have explicit type in the initialization expression, you have to have best names for members.

  3. It induces variable initialization. It is generally a good practice to initialize variable in the declaration, and compiler needs initializer to infer type for local variable declared with "var" keyword.

  4. It removes code noise. There are a lot of cases, when implicitly typed local will reduce amount of text developer needs to read, or rather skip. Declaring local variable from new object expression or cast expression requires specifying type twice, if we don't use "var". With generics it can lead to a lot of otherwise redundant code. Another example would be iteration variable in foreach over Dictionary.

  5. It doesn't require using directive. With var, you don't have explicit reference to type, as compiler infers type for you, so you don't need to import namespace when you need a temporary variable.

The cons are potentially less readable code. For instance the line int myInt = 0; is still more straightforward for most than var myInt = 0; but this is mainly due to the syntax we're all been looking at for years.




回答2:


var is not a data type, it is simply "syntactic sugar" for "let-the-compiler-infer-at-compile-time-what-actual-type-to-use".

So, you just need to understand the following type inferences:

var x = 4; //int
var y = 4.0; //double
var z = 4M; //decimal
var w = (string)null; //string


来源:https://stackoverflow.com/questions/3967993/pros-cons-of-var-datatype-in-net-3-5

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