views:

84

answers:

2

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? Just curious.

+11  A: 

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;
}
Developer Art
or store it in a variable to avoid the double look-up. either way, +1.
roe
@roe: Agree, it's better.
Developer Art
+2  A: 

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.

Greg
Of course! Duh... Thanks!
mickeyf