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.com/en-us/dotnet/fsharp/language-reference/interpolated-strings
2 Answers 2
Does 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.
Comments
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
9 Comments
string.Format.)printfn $"{123:``00000000``}" seems to do the right thing...$"%A{myRecord}" which will perform structured plain text formatting, which – without ToString overrides – will give details of the instance (rather than just the type name).
%format-specifierwhich 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.