Don't Kill Your Colleagues By Overusing Var

Tags: C#

With C# 3.0 came the keyword var.  It was a great forward leap for the language.  Unfortunately it’s become the lazy coder’s way of declaring a variable. It’s type inference run amuck. In a strongly typed language like good old C# types are our friends. So when should we use var?

Anonymous Types

The var keyword was a necessity in 3.0 because anonymous types were introduced. We needed a way to initialize them:

var myAnon = new { Name = "Anonymous Guy", Age = 49 };

What type is this? We don't know so we necessarily must use var.

Linq Queries Where We Don't Care What the Type Is

Here is a LINQ join.

var innerJoinQuery =
from cust in customers
join dist in distributors on cust.City equals dist.City
select new { CustomerName = cust.Name, DistributorName = dist.Name };

What type is innerJoinQuery? I don’t care. I am returning an anonymous type collection.

Where it is Obvious What the Type is

If it’s totally obvious from the right hand side of the statement what the type is, it’s reasonable to use var.

var myInstance = new MyType();

It’s pretty apparent that myInstance is of type MyType. Some people may even consider this more readable then

MyType myInstance = new MyType();

I don't consider var more readable but this use of var I can live with.

In my book which exists only in my head, clearly there are times when var should not be used.

Don't Obfuscate the Type

var things = GetABunchOfThings(size);

What are the things? I can't tell by reading the code. Annoying. Yes you can mouse over the variable to see the type, but that is a painful extra step. It’s not more readable. Var saved someone a few keystrokes at coding time, but var saps a developer's time every time they look at this code and var might possibly make them want to jump to their death.

Don’t Play Guess the Native Type

var length = 100;

Now is that a goddam int? A decimal? What’s the point of var here? Purely to annoy me? Stop pelting me with var!

Type inference is not like Mount Everest; don’t use it just because it’s there. Code readability is paramount. Coder laziness is not.

No Comments

Add a Comment