I am using ReSharper to help me spotting possible errors in my code, and, although not an error, it keeps complaining that I should use the var
keyword instead of explicitly typing variables on the declaration. Personally, I think it is much more clear for me and for anyone reading my code if I write
IList<T> someVar = new List<T>();
instead of
var someVar = new List<T>();
Knowing that there're no performance differences between both ways, should I ignore these hints or stick with the var
keyword?
Is it only a matter of taste or is it a good practice to implicitly type variables?
I see at least two reasons.
First, its the matter of DRY principle: don't repeat yourself. If in future you decide to change type of variable from List<>
to Stack<>
or LinkedList<>
, then with var
you'd have to change in one place, otherwise you'd have to change in two places.
Two, generic types declaration can be quite long. Dictionary<string, Dictionary<int, List<MyObject>>>
anyone? This doesn't apply to simple List<T>
, but you shouldn't have two code styles for different object types.