'var' is about being clear
The main debate about whether to use the var
keyword or not is about how readable the code is to you and other developers.
Just as if you were writing a story there is not definitive right answer. But let's look at some examples of this in plain English.
Jake said hello to Bill. He didn't like him so he turned and went the other way.
Who went the other way? Jake or Bill? In this case using the names "Jake" and "Bill" is like using the type name. And "He" and "him" is like using the var
keyword. In this case it might help to be more specific. The following for example is much clearer.
Jake said hello to Bill. Jake didn't like Bill so he turned and went the other way.
In this case being more specific made the sentence clearer. But that's not always going to be case. In some cases being specific makes it harder to read.
Bill likes books, so Bill went to the library and Bill took out a book that Bill has always liked.
In this case it would be easier to read the sentence if we used "he" and in some cases left out his name all together, which is the equivalent of using the var
keyword.
Bill likes books, so he went to the library and took out a book that he has always liked.
Those examples cover the gist, but they don't tell the whole story. In those examples there was only one way to refer to the person. Either by using their name or by using a more general term like "he" and "him".
In the case of code we have 3 ways we to help add clarity. The type, the variable name, and the assignment. Take this line of code for example:
Person p = GetPerson();
The question now becomes is there enough information in that line of code to help you figure out what's going on?
What about the following line of code? Would you still know what p
means in this case:
var p = GetPerson();
How about now:
var p = Get();
Or now:
var person = Get();
Or this one:
var t = GetPerson();
Or this:
var u = Person.Get();
Whether the keyword var
works in a given scenario depends a lot on the context of the code, like how the variables, classes, and methods are named. It also depends on the complexity of the code and the rest of the code surrounding it.
Personally I like to use the var
keyword it's more comprehensive to me most of the time. But I also tend to name my variables after the type so I'm not really losing any information.
That said sometimes depending on the context I make exceptions, such is the nature of anything complex, and software is nothing if not complex.