var is a feature of the C# programming language introduced back in 2007 with version 3.0. The use of this feature is still hotly debated within teams. I’m a proponent of its use and let me explain why arguments against its use don’t convince me other way.
‘var’ is strongly typed
Once the variable is declared, the compiler infers its type and validates any new assignment using that type. It follows the same rules as the
Type.IsAssignableFrom method. You cannot assign values where its type would make this method return false.
‘var’ makes refactoring much easier
Any long lasting project will go through multiple refactorings. I’ve had to refactor many projects and the use of
var can make a huge difference in productivity and code correctness.
Imagine that you have a method that returns
float and it’s used all over the place. Later you realize it’s precision is not enough and you change it to
var is not used, you have to go to every single place this method is used and change the variable type.
Now imagine the opposite, the method returns
double. Later, you realize that
float is good enough and you can save a lot of memory by doing this. On the previous case, the compiler would show you where you need to make the changes but not in this case as the .NET framework declares an implicit converter from
double. The code compiles but you may be wasting resources. You’re on you own to find where changes need to be made.
var, the variables will compile to the correct type on both cases.
‘var’ prevents value type boxing
.NET “boxes” value types that are cast to an interface type. This means that it’s copied to the heap and all method calls become virtual. This is what happens implicitly when assigned to a variable that is declared as an interface type.
GetEnumerator() usually returns
List<T>.Enumerator. Most people don’t notice this. Getting the type wrong will seriously affect performance.
var, “boxing” will be automatically avoided.
‘var’ can be readable without an IDE
IDEs, like Visual Studio, show the type of a variable in a tooltip when the mouse cursor hovers over it. An argument commonly used against the use of
var is that it should be easy to get the type even when not using an IDE. I would argue that it’s more important to have good variable and method names than it’s to write types all over the place. Good names is also great when you have to read someone else’s code or even your own after only a couple of weeks away.
This reasoning also holds true for fluent code style. I don’t see anyone using LINQ and assigning the result of each method to a variable with its type explicitly declared. The data just flows from one method to another and the code can be read like an English sentence.
Same with lambda expressions…
C# is great at inferring types and allow strongly-typed code all over.
var doesn’t contradict this and can be a great tool. Use it. You won’t regret.