[c#] Use of var keyword in C#

There is bound to be disagreement near the edge cases, but I can tell you my personal guidelines.

I look at these the criteria when I decide to use var:

  • The type of the variable is obvious [to a human] from the context
  • The exact type of the variable is not particularly relevant [to a human]
    [e.g. you can figure out what the algorithm is doing without caring about what kind of container you are using]
  • The type name is very long and interrupts the readability of the code (hint: usually a generic)

Conversely, these situations would push me to not use var:

  • The type name is relatively short and easy to read (hint: usually not a generic)
  • The type is not obvious from the initializer's name
  • The exact type is very important to understand the code/algorithm
  • On class hierarchies, when a human can't easily tell which level of the hierarchy is being used

Finally, I would never use var for native value types or corresponding nullable<> types (int, decimal, string, decimal?, ...). There is an implicit assumption that if you use var, there must be "a reason".

These are all guidelines. You should also think also about the experience and skills of your coworkers, the complexity of the algorithm, the longevity/scope of the variable, etc, etc.

Most of the time, there is no perfect right answer. Or, it doesn't really matter.

[Edit: removed a duplicate bullet]