String interpolation, string formatting and null coalescing operator at once

101 views Asked by At

I need this: If the following formatted value is null, display N/A. Otherwise, display the formatted value. It needs to be with string interpolation. I tried to do something like nested interpolation:

$"{$"({someValue:N0})" ?? "N/A" }"

but the result is just empty string. Using .NET 7.

1

There are 1 answers

0
MediocreFantasy On

I believe your issue here is that $"({someValue:N0})" will never evaluate to null becasue of the () outside the {}. What I would do here is the following:

(someValue == null ? "N/A" : $"({someValue:N0})"

This is essentially an inline if/else statement, where the portion before the ? is the condition, the first string (before the :) is what you get if the condition is true, and the second string is what you get if the condition is false.