0

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.

6
  • 3
    String interpolation will never yield null so the ?? "N/A" part is completely superfluous. Commented Nov 8, 2023 at 21:50
  • Thanks, it makes sense I guess. Could you suggest an alternative way to format a string with ?? or is it off the table entirely? Commented Nov 8, 2023 at 21:51
  • 1
    Alternative way without interpolation: someValue?.ToString("N0") ?? "N/A" Commented Nov 8, 2023 at 22:11
  • @madreflection Well, technically a custom string interpolation handler can do anything, including returning null Commented Nov 8, 2023 at 23:49
  • 1
    @Ed'ka: Edge case. Technically, you're right because it could yield null in the same way that you can set a non-nullable string to null with !, but I'd say that any interpolated string handler that yields null is broken because it didn't interpolate to a string instance. The interpolated string handlers implemented in the BCL don't yield null. Commented Nov 9, 2023 at 1:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.