Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add conditional to a null coalescing operation

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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…

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading