601

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

1 Answer 1

1090

According to the documentation:

The structure of an interpolated string is as follows:

{ <interpolationExpression>[,<alignment>][:<formatString>] }

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")}";
4
  • 29
    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")}");
    – Jan
    Jan 20, 2020 at 11:07
  • another example, ternary if with string interpolation in the condition: var foo = $"{x.Title} {(!string.IsNullOrEmpty(x.SubTitle) ? $"({x.SubTitle})" : string.Empty)}"; Jun 8, 2021 at 10:58
  • @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
    Dec 8, 2021 at 22:59
  • @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).
    – Jan
    Dec 11, 2021 at 8:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.