Search code examples
c#string-interpolationcsc

String Interpolation inside String Interpolation in C# results in compiler error


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?


Solution

  • 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)}."