I have an existing method return using a null-coalescing operation:
return GetOverrideColor(overrideFlags, colorUsage) ??
GetColor(colorExpression, field, purpose, defaultColor);
Is there a way to add an additional condition to this shorthand that would only run the GetOverrideColor method if x = true?
This is what I have in longhand:
CustomColor color = null;
if (overrideRequired)
color = GetOverrideColor(overrideFlags, colorUsage);
if (color == null)
color = GetColor(colorExpression, field, purpose, defaultColor);
return color;
>Solution :
I think you’re looking for this:
return (overrideRequired ? GetOverrideColor(overrideFlags, colorUsage) : null) ??
GetColor(colorExpression, field, purpose, defaultColor);
If overrideRequired is false, null is used for the left-hand operand to ??. If it’s true, GetOverrideColor(overrideFlags, colorUsage) is called and used as the left-hand operand to ??.
Alternatively, you might update GetOverrideColor to accept a flag for this (perhaps one of overrideFlags?), though calling a function passing in a value that tells it to just immediately return null may be a bit off…