I expected string interpolation to be the exact same for F# and C#.
This is fine for C#:
var x = $"{123:00000000}";
This does not work for F#:
printfn $"{123:00000000}"
Looking for an explanation.
I would expect MS docs to have a "F#/C# interpolation differences" but it ain't there
I expected string interpolation to be the exact same for F# and C#.
This is fine for C#:
var x = $"{123:00000000}";
This does not work for F#:
printfn $"{123:00000000}"
Looking for an explanation.
I would expect MS docs to have a "F#/C# interpolation differences" but it ain't there https://learn.microsoft/en-us/dotnet/fsharp/language-reference/interpolated-strings
Share Improve this question asked Mar 7 at 8:12 inwenisinwenis 4078 silver badges26 bronze badges 5 |2 Answers
Reset to default 5Does string interpolation work the same for C# and F#?
No! Or rather, "not quite".
This is covered by the documentation.
Short version, if the format specifier contains "unusual characters" then it needs to be quoted with double back ticks.
Eg. (from the docs)
let nowDashes = $"{System.DateTime.UtcNow:``yyyy-MM-dd``}" // e.g. "2022-02-10"
For completeness: F# supports three types of string formatting
- Plain text formatting: inbuilt, type-safe (checked by the compiler and tools). There are many methods supporting this (in F#'s core library's Printf Module).
- String Interpolation: as above. Something of a hybrid of C#'s interpolated strings and F#'s plain text formatting.
- You can of course call
String.Format
(et. al.) directly.
F# supports string interpolation, but it does not use string.format
internally. Use printfn $"{123.ToString("00000000")}"
instead, beacuase F# needs a more explicit conversion. Hope this helps
%format-specifier
which wouldn't be present in C#. I would say it's very rarely a good idea to expect anything to work exactly the same between two languages. – Jon Skeet Commented Mar 7 at 8:25