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)
var
here would help a little bit in detecting the error when changing method signature. However, for such a change, I'll always review all references anyway.IEnumerable<MyObject>
toTask<List<MyObject>>
then you are completely changing what the method does and so should have changed the method name too. Renaming fromGetResult
toGetResultTask
would have instantly then picked up all the places where the calling code needed changing.var
is very much a style thing. Some (like myself) use it everywhere. Others hate it so much they even define a type calledvar
to try and block it's use. It's a subjective thing. Finding objective reasons for either approach is hard.var
a lot, also tend to use a more declarative programming approach, avoid mutability, write shorter methods and classes, write unit tests (which would have failed after yourTask
change) etc. It's part of a mindset. Looking atvar
in isolation therefore misses the point to a certain extent.