592

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}";
Jim G.
  • 15,141
  • 22
  • 103
  • 166
Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
  • 11
    @Sinatr Updated link: http://thebillwagner.com/Blog/Item/2015-07-05-StringInterpolationandtheConditionalOperators – Nate Barbettini Oct 06 '15 at 13:48
  • The same applies to the [namespace alias qualifier (::)](https://msdn.microsoft.com/en-us/library/htccxtad.aspx). – Uwe Keim May 11 '16 at 08:32
  • Roslyn team related discussion: [Strange syntax error in interpolated string when using ?:](https://github.com/dotnet/roslyn/issues/12214) – mins Apr 30 '20 at 13:41

1 Answers1

1075

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")}";
Community
  • 1
  • 1
Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
  • 26
    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 '20 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)}"; – Guilherme Flores Jun 08 '21 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 08 '21 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 '21 at 08:14