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.
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
-
1Any reason not to use the .NET-style format specifiers as per learn.microsoft.com/en-us/dotnet/fsharp/language-reference/…? (That certainly gives the impression that they can be used - and I'd expect that those format specifiers would end up with a call to
string.Format
.) Commented Mar 7 at 8:29 -
For example,
printfn $"{123:``00000000``}"
seems to do the right thing... Commented Mar 7 at 8:32 -
It can be used, but does only work under certain conditions. The thing is, F#'s string interpolation ($"...") does not support :format specifiers directly for some reason. I think that may be the cause of the problem Commented Mar 7 at 9:10
-
That seems to contradict the documentation. Can you give a concrete example of a format specifier that doesn't work? I'd like to know more. Commented Mar 7 at 9:28
-
@JonSkeet one case is the %A formatting (eg.
$"%A{myRecord}"
which will perform structured plain text formatting, which – withoutToString
overrides – will give details of the instance (rather than just the type name).– RichardCommented Mar 7 at 9:32
%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.