myAudioSource = audio == null ? gameObject.AddComponent<AudioSource>() : audio; // working
// alternative
myAudioSource = audio ?? gameObject.AddComponent<AudioSource>(); // <--- not working?
NOTE: “audio” is a field from a baseclass
The first version was the org. code i copy&pasted, now VS + ReShaper “correctly” tells me that i can convert this expression to a ?? expression. The problem is that using the second expression the audiosource is not created?
I’m missing something, since from my point of view the two should be equal expressions?
Unity created some equality/inequality checks as some implicit casts which may disturb this a little bit. null may in Unitys case (everything inherited from UnityEngine.Object) not be a real null.
The first one will call the equality operator from UnityEngine.Object, the second does a real null check. In Unity == null means that the object is either really null or marked as destroyed.
This:
GameObject a = null;
GameObject b = a == null ? new GameObject() : a;
audio might do that internally but it might not be the same pattern as transform because a GameObject must have a Transform whereas it can optionally have an AudioSource.