In my opinion,
var should be used when either of the following is true:
- The type is anonymous (well, you don’t have any choice here, as it must be var in this case)
- The type is obvious based upon the assigned expression (i.e.
var foo = new TypeWithAReallyLongNameTheresNoSenseRepeating())
var has no performance impacts, as it’s syntactic sugar; the compiler infers the type and defines it once it’s compiled into IL; there’s nothing actually dynamic about it.
var can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:
var orders = cust.Orders;
I don’t care if Customer.Orders is
BindingList<Order> – all I want is to keep that list in memory to iterate over it or get its count or something later on.
Next, we consider some interesting limitations of the var keyword. You can’t assign a var to null. This will result in the CS0825 warning. You also can’t use var as a parameter type or a return value of a method.
One tip is to use var on generic types. The Dictionary type has verbose syntax—it uses a lot of brackets and letters and a comma. Some code becomes much easier to read when you use var. Var can even make code refactoring easier.
If you change a type name with refactoring, a var type local will not need to be changed.
Next, you can use var in a foreach-loop construct. This makes the loop syntax really simple. Simple often means easy to understand.