Incorrect Possible 'System.NullReferenceException' whille all null values have been checked
I don't understand why Resharper warns me for a possible NullReferenceException in this situation. Resharper shows the warning on both foo.Current and foo.Next in the last line of the HasValueChanged method.
private static bool HasValueChanged(Foo foo)
{
if (foo.Current == null && foo.Next != null) return true;
if (foo.Current != null && foo.Next == null) return true;
if (foo.Current == null && foo.Next == null) return false;
return foo.Current.FooBar != foo.Next.FooBar;
}
public class Foo
{
public Bar Current { get; set; }
public Bar Next { get; set; }
}
public class Bar
{
public string FooBar { get; set; }
}
Originally I used an XOR operation to check if jus one of the two values was null and I though maybe that was the reaseon ReSharper didn't see that all possible null scenarios were checked, bu as the above code shows, that wasn't the case. But just for reference: this was my acutal code:
private static bool HasValueChanged(Foo foo)
{
if (foo.Current == null ^ foo.Next == null) return true;
if (foo.Current == null && foo.Next == null) return false;
return foo.Current.FooBar != foo.Next.FooBar;
}
Also interesting to note: if I remove all the null-checks from the HasValueChanged method so I only keep the last line, Resharper no longer warns me about a possible NullReferenceException. Even though now, I really do have a possible NullReferenceException!
ReSharper 2023.2.20230731.174521 in VS Professional 2022
Please sign in to leave a comment.
Hello Dick,
Thank you for contacting us.
I successfully reproduced the issue and opened the corresponding bug report - https://youtrack.jetbrains.com/issue/RSRP-493612/Incorrect-Possible-System.NullReferenceException-whille-all-null-values-have-been-checked
Feel free to comment or vote for it.