Incorrect "possible null reference" warning?

i do some XML manipulation via LINQ to XML. For this i have written a function which returns the value of a XML-Attribute. The following code snippet shows a possible null reference warning:

2012-04-24 10h15_47.png

I can't see any reason for this warning. Is this a bug or do i miss something?

Regards
Klaus

2 comments
Comment actions Permalink

The ".Attribute" method can return null. Although you've checked that the attribute exists on the line above, R# has no way of knowing that both calls will return the same value. For example, the XML object might be modified on a different thread between the calls.

If you change your code as follows, you shouldn't see the error:

var attribute = instSpecifier.Attribute(pAttributeName);
if (attribute != null) return attribute.Value;



Alternatively, since it looks like you're returning an empty string if the attribute doesn't exist, you could use:

return (string)instSpecifier.Attribute(pAttributeName) ?? string.Empty;


The XAttribute and XElement classes define several explicit type conversions which return null when passed a null attribute or element. For example:

public class XAttribute : XObject
{
    ...
    public static explicit operator string(XAttribute attribute)
    {
        if (attribute == null) return null;
        return attribute.value;
    }
}

0
Comment actions Permalink

thanks for the explanation. It is the first time i use LINQ to XML, so i'm not so familiar with the details. Specially i didn't thought about possible threading issues.

0

Please sign in to leave a comment.