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:
I can't see any reason for this warning. Is this a bug or do i miss something?
Regards
Klaus
Please sign in to leave a comment.
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:
Alternatively, since it looks like you're returning an empty string if the attribute doesn't exist, you could use:
The XAttribute and XElement classes define several explicit type conversions which return null when passed a null attribute or element. For example:
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.