8

The following C# expression is resulting in a compiler error in my program:

$"Getting image from {location.IsLatitudeLongitude ? $"{location.Latitude} - {location.Longitude}" : location.Location}."

Shouldn't it be possible to use String Interpolation like that? Or is it just not possible to do this?

1
  • 1
    Using the ternary operator within string interpolation is a bit tricky: I think you have to add round braces. Commented Jan 20, 2017 at 11:24

2 Answers 2

7

As per the documentation, you need to use the following format when using the ternary operator inside string interpolation.

The structure of an interpolated string is as follows:

$ "{ <interpolation-expression> <optional-comma-field-width> <optional-colon-format> }"

Therefore you need to add a set of brackets after { and before the closing } like this:

$"Getting image from {(location.IsLatitudeLongitude ? $"{location.Latitude} - {location.Longitude}" : location.Location)}."
Sign up to request clarification or add additional context in comments.

Comments

4

I just tested this. As i commented, you need braces for a tenery operator:

$"Getting image from {(location.IsLatitudeLongitude ? $"{location.Latitude} - {location.Longitude}" : location.Location)}."

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.