Why is an object of type var infer and not an XmlNode in an XmlNodeList loop?

If one of the XmlNodeList elements is similar to this

foreach (XmlNode foo in xmlNodeList) {string baa = foo.Attributes["baa"].Value;} 

everything works as expected - foo is explicitly of type XmlNode, and ID.NET VS.NET shows methods and fields.

On the other hand,

 foreach (var foo in xmlNodeList) { string baa = foo.Attributes["baa"].Value; } 

does not compile because foo has an object type here. The output type sorts the work, but passes the object.

Apparently, the XmlNodeList elements do not have one specific type, but the purpose of the XmlNode instead of var does something implicit (casting or unpacking).

First question: what is the mechanism of this?

The second (related) question: how to find the types that can be used in this kind of loop? Does ID.NET ID help?

+8
c # xml type-inference
source share
3 answers

XmlNodeList implements only a generic IEnumerable interface, not something like IEnumerable<XmlNode> with generics. This prevents strong typing of its elements until you are properly configured, so the compiler has no choice but to match the implicit declaration of type object in your foreach.

If you insist on using the var keyword, you can use the XmlNodeList elements as follows:

 foreach (var foo in xmlNodeList.Cast<XmlNode>()) { string baa = foo.Attributes["baa"].Value; } 

But it is ugly and requires more keys. You can simply explicitly declare XmlNode foo , and let foreach drop it for you on the fly.

+9
source share

As BoltClock notes, XmlNodeList implements only IEnumerable .

The foreach automatically casts for you off-screen, so this:

 List<object> values = new List<object> { "x", "y", "z" }; foreach (string x in values) { ... } 

is completely legal and performs a throw (which may, of course, throw an exception) for each value.

It's not entirely clear to me what you mean by your second question, but I just recommend that you explicitly use the XmlNode in your loop. If you really want to use var , you can write:

 foreach (var foo in xmlNodeList.Cast<XmlNode>()) 

but for me it seems superfluous ...

+4
source share

The XmlNodeList was in the .NET Framework before it supported shared files. Because of this, it only implements the generic IEnumerable interface, not the generic IEnumerable<T> .
To find out what types may be in this list, you need to read the documentation. The best way is indexer .

BTW: The IDE has not been called by VS.NET since the release of Visual Studio 2005 :-) It has been called VS only since then.

+4
source share

All Articles