FormattableString
has been Introduced in C# 6.0. As we can use same string formatting using string
object why is there need of using FormattableString
or IFormattable
. Whats difference between three?
My Code
var name = "Pravin";
var s = $"Hello, {name}";
System.IFormattable s1 = $"Hello, {name}";
System.FormattableString s2 = $"Hello, {name}";
Above all there produces same result. i.e 'Hello Pravin'.
Can I get more elaborated answer on this if anyone has deep knowledge on same.
FormattableString
is a new type in .NET 4.6, and the compiler will only use it if you try to use it. In other words, the type of an interpolated string literal is normallystring
- built withstring.Format
- but can beFormattableString
(viaFormattableStringFactory
) if you ask for it.A
FormattableString
consists of the format string which would be passed tostring.Format
(e.g."Hello, {0}"
) and the arguments that would be passed in order to format it. Crucially, this information is captured before formatting.This allows you to adjust the formatting appropriately - most commonly to perform it in the invariant culture, often with the
Invariant
static method.When you assign an interpolated string literal to an
IFormattable
variable, that will useFormattableString
too. TheIFormattable.ToString(string, CultureInfo)
implementation ignores the first argument in this case, which is presumably why it uses explicit interface implementation.Sample code:
Sample results: