17

I'm trying to do something like

string heading = $"Weight in {imperial?"lbs":"kg"}"

Is this doable somehow?

2 Answers 2

29

You should add () because : is also used for string formatting:

string heading = $"Weight in {(imperial ? "lbs" : "kg")}";
Sign up to request clarification or add additional context in comments.

Comments

15

Interpolated strings can contain formatting definitions which are separated from the variable name by colons.

string formatted = $"{foo:c5}"; // 5 decimal places

Since the conditional operator (?:) also uses a colon, you have to use braces to make it clear for the compiler that you don't want a format specifier:

string heading = $"Weight in {(imperial?"lbs":"kg")}";

2 Comments

Right an precise explanation, +1
Now I understand. Thanks!

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.