1

Resharper gives a possible null reference warning for the Element method call just after it was cheked for null (TransformElementBad method), but everything is ok if I keep element value in some variable. Is ReSharper right and I should use its suggestion or it is a bug?

// JetBrains ReSharper 8.2.1 
// Build 8.2.1000.4556 on 2014-05-19T09:12:38

public class Transformer
{
    private void TransformElementBad(XElement field)
    {
        var format = string.Empty;

        if (field.Element("ViewFormatInfo") != null)
            format = field.Element("ViewFormatInfo").Value.Trim(); // ![got][1] warning here

        Console.WriteLine(format);
    }

    private void TransformElementGood(XElement field)
    {
        var format = string.Empty;

        var element = field.Element("ViewFormatInfo");
        if (element != null)
            format = element.Value.Trim();

        Console.WriteLine(format);
    }
}
bonzaster
  • 313
  • 2
  • 12

3 Answers3

1

The Value can be null that is why it is giving the warning, so you have to check for null before calling Trim(), if it is sure that there will always be Value in it then no need of null check.

format = field.Element("ViewFormatInfo").Value !=null ? field.Element("ViewFormatInfo").Value.Trim() : string.Empty; 
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
1

Answer from vendor: Element method is not pure and could not return the same result given the same arguments. So you have to copy its result into local variable if you want to avoid this warning https://youtrack.jetbrains.com/issue/RSRP-424149

bonzaster
  • 313
  • 2
  • 12
0

I ain't mean to do gravedigging here, but as no solution was present (only the explanation of this behavior), might as well share my thoughts with this thread.

So, while I cannot argue with JetBrains' position about this question, I noticed that you can avoid this annoying warning in C# 6 and later with null-conditional access:

var format = field.Element("ViewFormatInfo")?.Value.Trim();

Also, note that

The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute.

That means, calling Trim() method on Value property with null-condition will not throw NullReferenceException (as if Value itself was null), but simply returns null to the caller;

Konstantin K.
  • 168
  • 1
  • 6