Monday, 12 April 2010

When to use var in C#

The keyword "var" was introduced with C# 3.0. It allows you to declare a variable without having to specify the type within a method boy, as long as the variable is initialised in the same statement.

Its usage has been prompted by some parties including Microsoft (implicitly) and RSharper (explicitly). For example, some code snippets, e.g. foreach, in Visual Studio use var; and RSharper by default suggests replacing variable types with var when possible.

The use of var certainly provides convenience (and necessity in the case of anonymous types), especially when the type name is long and apparent, e.g.

ExecutionEngineException exception = new ExecutionEngineException();

You will be delighted to use var knowing that the compiler will infer the type for you in the above instance:

var exception = new ExecutionEngineException();

However, in cases where the type is not apparent, e.g。 when calling your a method, it is better to specify the type explicity, e.g.

List files = myClass.GetOpenFiles();

rather than using var:

var files = myClass.GetOpenFiles();


You may argue that this is not a big deal, since in Visual Studio, if you hover your mouse cursor over the method name, the return type will pop up. But it is an extra effort which you may want to spare when reading the source code, and if you have a few variables declared using var, the efforts build up.

More importantly, some methods may return a type that is counterintuitive to its name. For example, Enum.GetValues() returns an array of object, rather than a collection of values in the enum as the method name suggests.

In the following code snippet, PrintValueRight() which uses type (int) explicitly will print

1
2
3

PrintValueWrong() which uses var will print

Mon
Tue
Wed

So to avoid confusion and bugs, I suggest only use var with anonymous types and variable declarations that initialised through constructors so that the type is unambiguous.