a ?? b
- If
ais notnull=> returnsa. - Else (
aisnull) => returnsb.
I want to simulate something like its inverse (AFAIK there is no operator to do this):
- If
aisnull=> returna. - Else (
ais notnull) => returnsb.
The idea is that b would be the result of a function that receives a and needs to avoid null parameters. Like this: a XX fn(a) where XX would be the operator (if it exists).
My only two variants are:
a == null ? a : fn(a)a == null ? null : fn(a)
Is there any way to simplify this code?
Not sure exactly what you’re trying to accomplish? Something like this?
But the best solution IMHO would be to just have
fnreturn null if it is passed a null value.EDIT:
The method at the top is only an example. You might want to use something like this in a situation where you’ve got a LOT of the same operation over and over again in a specific area and you can’t change fn because it would make is easier to focus on the rest of the code and there’s a chance you might want to alter the null-handling behavior for all your operations at once in the future. (I’m assuming that is the case because you’re asking in the first place.) But I wouldn’t use this across an entire application because it isn’t clear what’s happening if you don’t have the
NullFnfunction right in front of you.