Wednesday 12 July 2017

To var or not to var

Bit of a change for this post.

When C# 3.0 was released by Microsoft, the var keyword was introduced.
This new keyword allowed the implicit typing of variables, according to their context in the source code. Unfortunately, this new feature has caused some confusion and some problems with readability of code. Therefore, this brief document aims to outline what var is, how it works and when (and when not) to use it.

What is var?

var allows us, as programmers, to reduce the amount of typing when declaring variables. For value types, this doesn’t really make much difference, but for complex reference types, this can reduce the amount of typing a great deal:

e.g.
dictionary<string,dictionary<string,List<int>>> complexItem = new dictionary<string,dictionary<string,List<int>>>();
can be replaced with:
var complexItem = new dictionary<string,dictionary<string,List<int>>>();

Not only does this reduce typing, and slightly enhance readability, it also reduces the possibility of errors in the declaration as we are only having to type out the structure of the type once.
var does this inference at compile time, not runtime. This means that when the compiler finds the above line, it translates it to:

dictionary<string,dictionary<string,List<int>>> complexItem = new dictionary<string,dictionary<string,List<int>>>();

This means that the variable created is not the same as a dynamic variable, and it can only be used in this way if the type is obvious (to the compiler) at compile time.

When not to use var?

var cannot be used in a declaration of a variable if the variable is not initialised:
var unintialisedVariable; // Compile time error
var should also not be used if the type is not obvious when reading the source code:
var newVariable = functionReturningAValue(); // What does this function return?
In this situation, the compiler will be able to determine the type, but it is not immediately obvious to anyone reading the source code. Therefore, the reader would have to find the function declaration to determine the type of the variable.