If one loops through an XmlNodeList like this
foreach (XmlNode foo in xmlNodeList) {string baa = foo.Attributes["baa"].Value;}
everything works as expected – foo is clearly of type XmlNode and the VS.NET IDE shows methods and fields.
On the other hand
foreach (var foo in xmlNodeList) { string baa = foo.Attributes["baa"].Value; }
is not compiling because here foo is of type object. Type inference sort of works but infers object.
Apparently, the elements of XmlNodeList are not of one defined type, but assigning them to XmlNode instead of var does something implicitly (casting or unboxing).
First question: what’s the mechanism behind that?
Second (related) question: how to find the types one can use in this kind of loop? Does the VS.NET IDE help?
XmlNodeListimplements only the non-genericIEnumerableinterface, and not something likeIEnumerable<XmlNode>with generics. This prevents strong typing of its elements until you cast appropriately, so the compiler has no choice but to map the implicit type declaration toobjectin your foreach.If you insist on using the
varkeyword, you can cast the elements ofxmlNodeListlike so:But that’s ugly, and requires more keystrokes anyway. You may as well just explicitly declare
XmlNode foo, and let the foreach cast it for you on the fly.