String Interpolation inside String Interpolation in C# results in compiler error [duplicate]
Asked Answered
B

2

7

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?

Balakirev answered 20/1, 2017 at 11:22 Comment(1)
Using the ternary operator within string interpolation is a bit tricky: I think you have to add round braces.Incandescent
C
6

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)}."
Coltin answered 20/1, 2017 at 11:32 Comment(0)
I
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)}."
Incandescent answered 20/1, 2017 at 11:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.