Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 944
Volker Avatar asked Feb 27 '17 18:02

Volker


2 Answers

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

string heading = $"Weight in {(imperial ? "lbs" : "kg")}";
like image 197
Roman Doskoch Avatar answered Oct 11 '22 16:10

Roman Doskoch


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")}";
like image 22
Thomas Weller Avatar answered Oct 11 '22 15:10

Thomas Weller