GetComponent() ?? Add() throws an error; GetComponent() == null ? Add : Get does not?

This is a bit odd and may end up being a “duh” moment, but for some reason this doesn’t work:

someComponent = gameObject.GetComponent<SomeType>() ?? gameObject.AddComponent<SomeType>();

It gives me an error saying There is no "SomeType" attached to "MyObject".

However, if I use this:

someComponent = gameObject.GetComponent<SomeType>() == null ? gameObject.AddComponent<SomeType>() : gameObject.GetComponent<SomeType>();

That works just fine.

I thought the A ?? B operator meant “if A is not null, use it, otherwise use B”.

I’m not sure what I’m missing, but I don’t get why A == null ? B : A works but A ?? B does not.

Unity handles the null comparison in a custom way

In fact, the references to the Unity Objects are not real nulls, but fake nulls

  1. When a MonoBehaviour has fields, in the editor only, we do not set those fields to “real null”, but to a “fake null” object. Our custom == operator is able to check if something is one of these fake null objects, and behaves accordingly.

Unfortunately, this custom overload has downsides, like the one you are facing.

It behaves inconsistently with the ?? operator, which also does a null check, but that one does a pure c# null check, and cannot be bypassed to call our custom null check.