Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why var used in foreach for XmlNode does not deduce real type, only object?

Let cls be of type XmlNode

Following statement allows me to access child nodes:

foreach (XmlNode child in cls.ChildNodes)

Now when I try to use var:

foreach (var child in cls.ChildNodes)

then the type of child is not XmlNode, only object. I cannot use child.NodeType, compiler says:

object' does not contain a definition for 'NodeType

Why is this?

like image 520
Suma Avatar asked Jun 14 '13 11:06

Suma


1 Answers

ChildNodes is of type XmlNodeList which is defined as

public abstract class XmlNodeList : IEnumerable, IDisposable

Its enumerator returns an object. When you use XmlNode instead of var, .net automatically casts object to XmlNode. But when you use var, child is treated as an object.

like image 68
Mehmet Ataş Avatar answered Oct 12 '22 22:10

Mehmet Ataş