C# - What is the var keyword? Is it better to declare variables using it?

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 in this post I will describe what the "var" keyword is, the documentation for "var" can 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 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.

Meaning that:

var i = 1; // implicitly typed

Will be something like the following at compile time:

int i = 1; //explicitly typed

In my current work environment 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. Using the "var" keyword 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 mentioned 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 code base uses 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 your code base.

Did you find this helpful? Please leave a comment down below!