Microsoft.Unity.Analyzers/doc/USP0018.md

931 B

USP0018 Unity objects should not be used with throw expressions

UnityEngine.Object should not be used with throw expressions.

Suppressed Diagnostic ID

IDE0016 - Use throw expression

Examples of code that produces a suppressed diagnostic

using System;
using UnityEngine;

class Camera : MonoBehaviour
{
    public MonoBehaviour value;
    public void Method(MonoBehaviour value) {
        if (value == null)
            throw new ArgumentNullException(nameof(value));

        this.value = value;
    }
}

Why is the diagnostic reported?

Under normal circumstances, this code can be simplified to this.value = value ?? throw new ArgumentNullException(nameof(value)).

Why do we suppress this diagnostic?

Unity has overridden the == operator for UnityEngine.Object. If you use ?? operator with those objects, it will not behave as expected because it checks for null in a different way.