The var keyword

C# 3.0 introduced the anonymous types and the var keyword to be able to use them:

var variableTypeAnonyme = new
    {
        Website= "http://www.meziantou.net/",
        Author="Meziantou"
    };

However, the var keyword can be used to declare any type (string, int, …) if the type is inferable by the compiler:

var a = 1;
var b = "toto";
var c = obj as Customer;
var d = null; // not valid

The problem is that this can bring a lack of readability especially when you are using a text editor without toolip to do a code review such as on GitHub. In the previous example there is no problem but in cases like the following:

var a = 1;
// 15-20 lines after.
var b = a; // What's the type of b?

var toto = MyMethod(); // Cannot get the type of toto easily

Is it really harder to write the full type?

int a = 1;
// 15-20 lines after.
int b = a;

To conclude, the var keyword has its utility, however you should not use it everywhere if you don't want do lose in readability.

Leave a reply