With in the introduction of anonymous types in C# we got the var keyword.
Now people use var everywhere instead of the correct type. The reasons I've heard given for this are:
- It makes refactoring easier
- It's shorter
- it improves readability
A common example might be
var result = client.GetResult(query);
is better than:
MyObject result = client.GetResult(query);
Because if you refactor GetResult to return a different object; for example:
MyOtherObject result = client.GetResult(query);
you don't have to also refactor the calling code.
However I recently had to do the following refactoring
IEnumerable<MyObject> GetResult(query)
to
Task<List<MyObject>> GetResult(query)
The calling code was along the lines of
//return true if there are any results
var result = client.GetResult(query);
if(result != null)
{
return true;
}
return false;
Which after the refactoring would still compile and always return true. Whereas the explicitly typed form would have thrown a compilation error.
So. The question is. Given that there are downsides to using var instead of the explicitly typed variable. Is it simply a case of coding style preference, or are there clear reasons to use, or not use var in this fashion? (ie. other than where required with anonymous types)