Since the introduction of the var keyword in the C# 3.0, its use has been strongly debated. I have waited for some time to let the dust settle before forming an opinion.
The main argument against its use that I hear most is the use of var can make source code less readable for others.
foreach (var item in someList) {…} // Type of 'item' is not clear.
var something = someObject.SomeProperty; // Type of 'something' is not clear.
var something = someMethod(); // Type of 'something' is not clear
As I see it the problem is not with the use of the var keyword but with the use of vague variable names. You should be using descriptive variable names.
foreach (var customer in customers) {…} // Type is clear.
var orders = customer.Orders; // Type is clear.
var order = GetOrder(); // Type is clear
If you still need validation of the type. Hovering over the var keyword will show you the type.
I think that it reduces code noise. In the case that you wish to keep a list of customer order in memory and interate over it or get it count later. I would rather use:
var order = custer.Orders;
Rather than:
ObservableCollection<Order> order = custer.Orders;
The type name is just noise to me. If you use a generic list, then what is the difference than using var as well?
C# is a strongly typed language. You can check the MSDN documentation here. It states that an implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.
Using the following method:
public int ReturnValue()
{
var a = 5;
int b = 5;
return a + b;
}
The IL will look like the following. Notice that both the int and the var compile down to an int32.
.method public hidebysig instance int32 ReturnValue() cil managed
{
// Code size 9 (0x9)
.maxstack 1
.locals init ([0] int32 result,
[1] int32 CS$1$0000)
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: br.s IL_0007
IL_0007: ldloc.1
IL_0008: ret
} // end of method VarKW::ReturnValue
You should have nothing to fear with the use of var were appropriate. In my experience it only helped me to create good decoupled design of my components.