629

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

1144

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")}";
Sign up to request clarification or add additional context in comments.

4 Comments

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).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.