C#'s ??-Operator in Unity

Hi folks,

can anyone explain me the diffrence between this two code segments?
They should do the same, but somehow the ??-Operator fails

public InventarItem(InventarItem _original)
{
m_ID = _original.m_ID;
m_Name = _original.m_Name;
m_Picture = _original.m_Picture ?? InventarController.Instance.m_DefaultPicture; // does not work if _original.m_Picture is null
}
public InventarItem(InventarItem _original)
{
m_ID = _original.m_ID;
m_Name = _original.m_Name;
m_Picture = _original.m_Picture != null ? _original.m_Picture : InventarController.Instance.m_DefaultPicture; // works
}

Unity has overridden the == operator to return things as null, even when they’re not, and vice versa.

When you call Destroy(gameObject), the gameObject is not instantly removed from memory - it’s kept around in a “destroyed” state. Unity’s == override takes this into account, so if you compare a “destroyed” state gameObject to null with ==, it works as you’d expect. But, the null coalescing operator (??) doesn’t have a clue what’s going on, so it sees the object and returns it as non-null.

Sucky, but that’s why.

4 Likes

Ok, thank you, this makes a lot of sense…

So the null coalescing operator won’t work with any classes provided by unity?

Nothing that derives from UnityEngine.Object

Is there a reason for overloading == and not ??, or is overloading ?? something we should request from Unity?

AFAIK you actually can’t overload the coalescing operator.

C# doesn’t allow ?? overrides - just ==.