Volker
Volker

Reputation: 1847

How do I use string interpolation with string literals?

I'm trying to do something like

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

Is this doable somehow?

Upvotes: 17

Views: 4251

Answers (2)

Roman
Roman

Reputation: 12201

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

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

Upvotes: 28

Thomas Weller
Thomas Weller

Reputation: 59640

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")}";

Upvotes: 15

Related Questions