I was never ‘taught’ c# – I’ve grown into it from other languages and there are certain nuances and quirky syntax that I might have read/seen at one point or another, but forgotten. It’s with that in mind that I’m sharing this recent ‘discovery’ by me.
C# has a ?? operator. It’s kind of like the standard conditional operator ?: but is specifically setup as a null check shortcut.
These two sections of code are functionally equivalent
parentToggle = gameObject.GetComponent(); if (parentToggle==null) parentToggle = gameObject.GetComponentInParent();
parentToggle = gameObject.GetComponent() ?? gameObject.GetComponentInParent();
In other words, ‘arg1 ?? arg2’ is the same as saying return arg1, unless arg1 == null in which case return arg2.
You could also use ‘arg1!=null?arg2:arg1’ but the ?? pattern is less typing 🙂