Skip to content

Latest commit

 

History

History
32 lines (22 loc) · 1.26 KB

File metadata and controls

32 lines (22 loc) · 1.26 KB

USP0022 Unity objects should not use if null coalescing

We have a dedicated diagnostic UNT0029 to prevent is-null check with UnityEngine.Object. But IDE0270 will suggest to use is-null check over reference equality method.

Suppressed Diagnostic ID

IDE0270 - Null check can be simplified (if null check)

Examples of code that produces a suppressed diagnostic

using UnityEngine;

class Camera : MonoBehaviour
{
	public void M()
	{
		Camera item = FindItem() as Camera;
		if (item == null)
			throw new System.InvalidOperationException();
	}

	MonoBehaviour FindItem() => null;
}

Why is the diagnostic reported?

Under normal circumstances, if (item == null) throw new System.InvalidOperationException() can be simplified to Camera item = FindItem() as Camera ?? throw new System.InvalidOperationException();.

Why do we suppress this diagnostic?

Unity has overridden the == operator for UnityEngine.Object. If you use the == operator to compare a UnityEngine.Object to null, it will return true if the UnityEngine.Object is destroyed, even if the object itself isn't actually null. The ?? operator cannot be overridden in this way, and therefore behaves inconsistently with the == operator, because it checks for null in a different way.