The var keyword

 
 
  • Gérald Barré

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

C#
var variableTypeAnonyme = new
{
    Website = "https://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:

C#
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 tooltip to do a code review such as on GitHub. In the previous example there is no problem but in cases like the following:

C#
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?

C#
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.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub