To VAR or not to VAR?

C#’s VAR keyword is very useful. It was introduced originally (for the most part at least) to allow dynamic language features and use of anonymous types.

Since I don’t use those features very often, what I really like is that it gets rid of unnecessary junk in your code. Instead of this nonsense…

Dictionary<string, string> myval = new Dictionary<string, string>();

… we have this:

var myval = new Dictionary<string, string>();

Much nicer!

However, sometimes var makes code harder to understand. I often come across code like this:

var people = GetPeople();

This is wonderfully concise, but if you are new to the code it can be confusing. What are we getting back? A list of strings, people from the database, custom view models?

The only way to find out is to hover your mouse over the method and see. Not a big deal, sure, but it means the poor developer has to make a greater effort to understand the code, and that’s a bad thing.

So when to VAR and when not to? I follow these rules:

  1. Don’t use var when retrieving getting a result from a method. The result is more verbose, but more understandable.
var people = GetPeople();
PersonViewModel[] people = GetPeople();
//Also Yes.
var people = (PersonViewModel[])GetPeople();

2. Ignore the previous rule when writing unit tests! People stop testing when tests become too brittle. For this reason I would sacrifice a little readability and ensure tests don’t break for tiny type changes.

3. For simple value types, use the type name instead. It’s clearer and you don’t sacrifice readability.

var shouldProcess = false;
//Clearer, with only one extra character.
bool shouldProcess = false;

4. For all other situations, when you can see what type a variable is by looking at where it is declared, use VAR.

var d = new Dictionary<string, string>();
var a = new { AnonymousType = true };
Show your support

Clapping shows how much you appreciated willemodendaal’s story.