#804 – Tradeoffs when Using the var Keyword
March 20, 2013 3 Comments
You’d most often use the var keyword, indicating an implicit type, in the following situations:
- For anonymous types (var is required)
- As the type of the result of a LINQ expression
- To avoid duplicating a long type name
You should end up using var if its use is required (for anonymous types) or if using var improves the readability of your code.
You must be careful, however, in using var to simplify your code. In many cases, while its use may make writing your code easier, the omission of a type can make the code less readable, because the person later reading the code may need to first determine the variable’s type before being able to use it.
A good rule of thumb is to use strongly typed variables by default and only use var when it is necessary.