Jeroen Kruis

freelance software engineer

.NET, Episerver, Azure, performance, code quality

Using Var

Variables that are declared at method scope can have an implicit "type" var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

Usage of "var" allows for cleaner code, but it also makes it easier to write code that is harder to maintain. To prevent that, there is a simple guideline: code that creates a new variable should mention the type of that variable once.

What we all want to prevent is repetitive type declarations like this: List<Models.Item> items = new List<Models.Item>(); In this case, using var leads to a cleaner declaration without the tedious type repetition: var items = new List<Models.Item>();

The danger lies in variables that are instantiated with calls to a function: var items = GetItems();
string name = items.FirstOrDefault?.Name;
So far, so good. But if the return type of GetItems() is changed to, say, Models.Item2 and Item2 does not have a Name property, then the second line of code will generate an error.

And therein lies the problem, because it is the first line of code where the error begins. Putting the type in the first line of code will move the error to the first line, making for more readable code.

The solution is easy. Always include the type in a variable declaration: List<Models.Item> items = GetItems();
var items = new List<Models.Item>();