开发者

Why can one null return be tested but another throws an exception?

开发者 https://www.devze.com 2022-12-31 17:11 出处:网络
I want to test if an xml attribute is present. Given this: XmlAttributeCollection PG_attrColl = SomeNodeorAnother.Attributes;

I want to test if an xml attribute is present. Given this:

XmlAttributeCollection PG_attrColl = SomeNodeorAnother.Attributes;

This first test works:

if (null != PG_attrColl["SomeAttribute"])   

"GetNamedItem" is supposed to return null, but the following test throws an exception complaining about the null it returns.

if (null != PG_attrColl.GetNamedItem("SomeAttribute").Value;)

Why the difference开发者_C百科? Just curious.


Because if GetNamedItem has returned null, you can't call for its Value member.

if (null != PG_attrColl["SomeAttribute"])
{
    string value = PG_attrColl.GetNamedItem("SomeAttribute").Value;
}

Or

object someAttributeNullable = PG_attrColl.GetNamedItem("SomeAttribute");
if (null != someAttributeNullable)
{
    string value = someAttributeNullable .Value;
}


if (null != PG_attrColl["SomeAttribute"])

Here you are checking to see if the Attribute is null

if (null != PG_attrColl.GetNamedItem("SomeAttribute").Value;)

Here you are checking to see if the Value of the attribute is null. The code is trying to access the attribute first, which is null, throwing an exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消