Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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();

It's a syntactic sugar that cuts down the keystrokes.

The compiler derives the type of variable on the LHS, by evaluating the expression on the RHS.

So a code like below:

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

is transalted by the compiler to:

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

The compiler is just so kind doing some of our typing.

My rule of thumb:

You should use var if the code is meant to be generic; i.e. if it would probably work correctly if the type changed in the future.

Using var wouldn't hurt your performance because the compiler does all the work. It's shorter then typing MyDatabaseModel model.

And another reason to use var is that you can see at the right side what kind of type it is.

The last reason to use it is for anonymous types (whenever you don't know the types).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top