sonnyb
sonnyb

Reputation: 3504

ReSharper warning for Possible System.NullReferenceException despite implicit null check

I am getting a ReSharper (2018.1) warning for Possible 'System.NullReferenceException' when I check for null implicitly with if (obj) instead of if (obj ! = null).

For example:

using JetBrains.Annotations;
using UnityEngine.UI;

public class CanBeNullTest : MonoBehaviour
{
    [CanBeNull] public Button Button { get; set; }

    private void EnableButton_explicitCheck()
    {
        if (Button != null) Button.enabled = true;
    }

    private void EnableButton_implicitCheck()
    {
        if (Button) Button.enabled = true;
    }

    //private void EnableButton_cSharp6()
    //{
    //    // null propagating operator is not available in C# 4
    //    Button?.enabled = true;
    //}
}

Only the implicit null check shows the ReSharper warning:

ReSharper-null-check-warning

I looked at the ReSharper page for "Why is ReSharper suggesting this" and the links there, but I couldn't find an explanation for this.

Is this a ReSharper limitation? Or is it incorrect or bad style to check for null implicitly?

Upvotes: 2

Views: 461

Answers (2)

Won Jun Bae
Won Jun Bae

Reputation: 5389

Although it doesn't actually produce a NullReferenceException, because your Button can be null and the if statement triggers an implicit conversion to boolean that produces the NullReferenceException, it is still valid warning in general.

Something similar in Java, Check if null Boolean is true results in exception

If you don't like extra null checks, you may be able to do the C# equivalent of the following Java code,

if (Boolean.TRUE.equals(value)) {...}

Upvotes: 2

sonnyb
sonnyb

Reputation: 3504

The if (Button) involves an implicit conversion to bool, which doesn't produce a NullReferenceException in this case, but it is a valid warning in general.

Upvotes: 1

Related Questions