Possible Duplicate:
Advantage of var keyword in C# 3.0
yesterday I stumbled upon a recomendation from MS, that I should use var, when ever possible:
http://msdn.microsoft.com/en-us/library/ff926074.aspx
I always thought that using the correct Type would help documenting the code and also help findig bugs at compile time.
What is the reason behind this recomendation?
Best Thomas
var requires less typing. It also is shorter and easier to read, for instance, than Dictionary<int,IList> . var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it's used.
The use of var helps simplify your code, but its use should be restricted to cases where it is required, or when it makes your code easier to read. For more information about when to use var properly, see the Implicitly typed local variables section on the C# Coding Guidelines article.
Implicitly typed variables are those variables which are declared without specifying the . NET type explicitly. In implicitly typed variable, the type of the variable is automatically deduced at compile time by the compiler from the value used to initialize the variable.
In Java, var can be used only where type inference is desired; it cannot be used where a type is declared explicitly. If val were added, it too could be used only where type inference is used. The use of var or val in Java could not be used to control immutability if the type were declared explicitly.
Well the recommendation has:
Coding Convention - Implicitly Typed Local Variables
Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.
Its not always.
Also it has:
Do not use var when the type is not apparent from the right side of the assignment.
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();
Using implicit typing does NOT mean that the variable is not strongly-typed. It means that the compiler implies the type from the right-hand side of the statement.
var i = 1;
i
is defines as having type int
. It's exactly the same as saying int i = 1;
but the type is implied.
Similarly, the following code is a lot easier to read:
var pairs = new List<pair<int, IEnumerable<string>>>();
than if you had to type:
List<pair<int, IEnumerable<string>>> pairs = new List<pair<int, IEnumerable<string>>>();
and yet the results are exactly the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With