Unity Tidbit: Null Coalescing Null Propagation With Nullable Structs

You know Null Propagation, right? If you need a value but you’re not sure the object exists and is initialised so you add a little ? before the value call you want? You know, if you have an array and you need array[0] but you’re not sure array is not null, you just write…

array?[0]

This way, the call doesn’t throw and, worst case, you get a null.

But what if it’s supposed to be an array of primitives like integers or anything not nullable? You can’t just do…

int number = array?[0];

The compiler gets angry at you for trying to assign a Nullable<int> into an int. That’s a big no no.

Well, what doesn’t work with Null Propagation works with Null Coalescing!

int number = array?[0] ?? 0;

This way, the first ? checks if the array is null. If it’s not, you get the first value. If it is, you get a null and the next ?? checks if the left side is null. If it is, it gives you 0 instead. Now you’re assigning ints to ints and everything is cool.

This also works great when you want optional parameters but your parameters don’t exactly have well defined default values or you want to use default values for your parameters that are not compile constants.

void Method(Vector3? positionOffset = default)
{
    Vector3 localPositionOffset = positionOffset ?? Vector3.zero;
    // more logic...
}

Because Nullable types’ default value is null.

You’re welcome. 🖖


Posted in No Category and tagged , , , by with comments disabled.