It seems that more and more C# code I read uses the var type identifier:
foreach (var itemChange in ItemChanges)
{
//...
}
No. Use var
where it improves readability and vice versa.
In general no technical reason. Readability - in either direction - is the only real factor.
However, one small caveat is that var
will infer the static type of the variable. If you want a sub or super class type you'll need to do the casting yourself. In the case of a foreach
, as in your example, you can usually get downcasting performed for you "for free" just by declaring your loop variable with the subclass type.
The classic example is iterating over an XML NodeList that you know is a list of XmlElement
, but Nodelist
is typed as a collection of XmlNode
s. Of course you can use a cast or an as
to get back the type you want, but that would seem to defeat the purpose of using type inference :-)
Of course, the compiler will let you know about this as soon as you try to use a member of the node that is only available to XmlElement
- so it's still not strictly a technical difference.
Another thing that is a little annoying is that if you use a tool like Resharper, it's very aggressive about suggesting you use var
in every possible situation. It's particularly annoying when it recommends you change, for example, an int
declaration into a var
!
However, unless you turn that feature off, you'll get less "noise" from Resharper the more you use var
.