ChatGPT解决这个技术问题 Extra ChatGPT

How to use the ternary operator inside an interpolated string?

I'm confused as to why this code won't compile:

var result = $"{fieldName}{isDescending ? " desc" : string.Empty}";

If I split it up, it works fine:

var desc = isDescending ? " desc" : string.Empty;
var result = $"{fieldName}{desc}";
@Sinatr Updated link: thebillwagner.com/Blog/Item/…
The same applies to the namespace alias qualifier (::).

C
Community

According to the documentation:

The structure of an interpolated string is as follows: { [,][:] }

The problem is that the colon is used to denote formatting, like:

Console.WriteLine($"The current hour is {hours:hh}")

The solution is to wrap the conditional in parenthesis:

var result = $"Descending {(isDescending ? "yes" : "no")}";

Even more interesting example is this one when you need to use a nested interpolation string: Console.WriteLine($"Cargo Weight: {(ship.WeightAvailable ? $"{ship.Weight:0.00}" : "n/a")}");
another example, ternary if with string interpolation in the condition: var foo = $"{x.Title} {(!string.IsNullOrEmpty(x.SubTitle) ? $"({x.SubTitle})" : string.Empty)}";
@Jan And yet even the example you give doesn't compile, and yet ReSharper has no problem disambiguating it (since it knows to offer a code fix).
@MgSam It would help if you tell the error and your development setup. I tested my example again (copy/paste it) using VS2019 and VS2022 using .NET Core 2 till .NET Core 6 and also .NET 2 to .NET 4.8. All compiled fine (if you have a Ship class with a bool WeighAvailable and double Weight public properties/attributes of course).