5

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?

Thomas Gassmann
  • 737
  • 1
  • 13
  • 27
  • 1
    Using the ternary operator within string interpolation is a bit tricky: I think you have to add round braces. – Thomas D. Jan 20 '17 at 11:24

2 Answers2

5

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)}."
Kevin Holditch
  • 5,165
  • 3
  • 19
  • 35
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)}."
Thomas D.
  • 1,031
  • 6
  • 17