Why should I use implicit types (var) when possible?

Possible duplicate:
The advantage of the var keyword in C # 3.0

Yesterday I came across a recommendation from MS that I should use var whenever possible:

http://msdn.microsoft.com/en-us/library/ff926074.aspx

I always thought that using the right type would help document the code, and also help find errors during compilation.

What is the reason for this recommendation?

Best thomas

+4
source share
5 answers

Using implicit typing does NOT mean that a variable is not strongly typed. This means that the compiler implies a type from the right side of the statement.

var i = 1; 

i defined as having type int . This is exactly the same as the expression int i = 1; but implied by type.

Similarly, the following code is much easier to read:

 var pairs = new List<pair<int, IEnumerable<string>>>(); 

than if you typed:

 List<pair<int, IEnumerable<string>>> pairs = new List<pair<int, IEnumerable<string>>>(); 

and yet the results are exactly the same.

+1
source

Ok, recommendation:

Coding Convention - Implicit Typed Local Variables

Use implicit typing for local variables when the type of the variable is obvious on the right side of the job or when the exact type is not important .

This is not always the case.

He also has:

Do not use var if the type is not displayed on the right side of the destination.

An example from the same source:

 // When the type of a variable is not clear from the context, use an // explicit type. int var4 = ExampleClass.ResultSoFar(); 
+7
source

It is syntactic sugar that shortens keystrokes.

The compiler infers the type of the variable in LHS, evaluating the expression in RHS.

So, the code as below:

 var fStream = new FileStream("file", Filemode.Open); 

Translated by the compiler to:

 Filestream fstream = new FileStream("file", Filemode.Open); 

The compiler is just so kind, doing some of our commands.

+4
source

My rule:

You should use var if the code is for general ; that is, if it is likely to work correctly if the type has changed in the future.

+2
source

Using var will not hurt your performance because the compiler does all the work. This is shorter than typing MyDatabaseModel model .

And another reason for using var is that on the right side you can see what type it is.

Last reason to use it for anonymous types (whenever you don't know types).

0
source

Source: https://habr.com/ru/post/1436076/


All Articles