Why is it a best practice to use var in c#?

Curiosities of the C# programming language...

The var keyword might appear a little bit deceiving sometimes, specially when involving Linq in the equation. Some developers (particularly novice ones) can't seem to draw the line between two things that are separate concepts. So, what is the best practice when using var in C#?

Var is a keyword that when found by the compiler, it tells it to 'infer' the type for the local variable in play.

var x = new List<int>();

This is exactly the same as:

List<int> = new List<int>();

In that previous example the compiler easily infers that var will be of type List<int>.

In another basic example, this:

var pieces = "hello".Split();

is equals to this:

string[] pieces = "hello".Split();

So in here, var is only helping you to write less clutter in order to define a type. Imagine the following declaration:

Dictionary<string, Dictionary<int, string>> myDir = 
            new Dictionary<string, Dictionary<int, string>>();


var myDir = new Dictionary<string, Dictionary<int, string>>();

but again, there are developers who might argue that you must explicity declare what you want in order to be clear in the code. In a way, to be clear on what is going on. Some other developers might want to go directly on using the shorter approach by using var.

So far, on the previous cases, there is no specific (or best practice/bad practice) way on using var. Again, until now is entirely optional.

It becomes mandatory (or necessary) when we are using (projecting) anonymous types. For example, you can define the following object:

var person = new { FirstName = "John", LastName = "Smith" };

The above case is true, but rare (in my opinion). I think this happens more often when we use linq (it comes into the picture).

So, with Linq:

var planets = new [] { "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune" };
var result = planets.Where(p => p.Length > 5).Select(p => new { Name = p, Length = p.Length });