Local type inference allows using var everywhere for local variable declaration. While this is syntactically correct, it is not a good practice, at least in my opinion. I tried to write down what could be a set of best practices using local type inference and I'd like to receive some feedback...
In general, you should use the var keyword when it is unavoidable (like for anonymous types that we will describe later). Conversely, you should use an explicit type when there is no initializer, when a type cannot be inferred (e.g. if the initializer is a lambda expression) or when the inferred type is not the one you want (e.g. too specific).
In any case, you should choose between var and an explicit type using the one that improves the code readability. What is a readable code might be subjective: the following list represents what are practices that in my opinion improve code readability.
- DO use var for anonymous types
var c3 = new { Name = "Tom", Age = 31 };
- DO use var for query expressions
var query = from c in customers where c.Discount > 3 select c;
- DO use var for complex generic types (this is a more general case that includes query BLOCKED EXPRESSION
- CAN but SHOULD NOT use var for new results in case of known type instance
var customer = new Customer();
var numbers = new int[] { 1, 3, 5, 9 };
- DO NOT use var for constant
var x = 5; // Bad Practice
- DO NOT use var for simple expression assignments
var amount = customer.Amount; // Bad Practice
var x = y / z; // Bad Practice
var count = list.Count(); // Bad Practice
What do you think about this? Let me know your opinion, thanks!