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

I shouldn’t have had to mention this but there are still people that believe it behaves just like its Javascript homonym. The closest you can get in C# to that behavior is by using the dynamic keyword.

‘var’ makes refactoring much easier

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 double. If 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 float to double. The code compiles but you may be wasting resources. You’re on you own to find where changes need to be made.

When using var, the variables will compile to the correct type on both cases.

‘var’ prevents value type boxing

GetEnumerator() usually returns IEnumerator<T> but List<T>.GetEnumerator() returns List<T>.Enumerator. Most people don’t notice this. Getting the type wrong will seriously affect performance.

When using var, “boxing” will be automatically avoided.

‘var’ can be readable without an IDE

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


NOTE: C++ 11 introduces an equivalent auto keyword. Scott Meyers wrote in his “Effective Modern C++” book a great explanation on why you should also use it.

Principal Engineer @ Farfetch - Future Retail Lab

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store