This post comes from a question I answered on stack overflow earlier. The question was about the use of datetimes. I used
var in my reply to instantiate 2 variables. Which sparked even further questions. So what is this
The documentation for
varcan be found here.
First off, there is no "magic" about the
var keyword. The type will be decided at compile time. Meaning there is no performance hit, and there is no resolving going on at runtime.
var is simply a placeholder for the actual type, meant to be make code easier to read and comprehend. It is also known as a "Implicitly typed local variable". So if the compiler cannot determine the type the build will fail.
var i = 1; // implicitly typed
Will be something like the following at compile time
int i = 1; //explicitly typed
In my current work enviroment everyone uses
var and most think that it makes code more readable. To be honest I mostly use it out of habit. It is neat that: if you have a method that returns a type and you store that in a variable. Then you if change the return type of the function you do not have to change the type of the variable. Since it is
var(implicit). This makes it more convenient to change parts of your code. I believe that
var cancels out some of the noise in code like types with long names and generic types.
Most arguments against
var is that it hides information or that developers feel that they lose "control" (too much magic). I believe this is a normal response, and very much in the nature of a developer. We want to know things and we want control over what happens in our code.
I see no argument for not using
var, but I understand that it takes some time to get used to.
var is often convenient. However as I said, it is mostly about readability. If you or your team, does not think the
var keyword makes your code more readable, then avoid it.
What I think is most crucial is that the codebase use either explicit or implicit. Having
var used in one line and an explicit type in the next makes it even more confusing. Set a standard for the project.