Page 195 - CSharp/C#
P. 195
A new type, System.FormattableString, represents a composite format string, along with the
arguments to be formatted. Use this to write applications that handle the interpolation arguments
specifically:
public void AddLogItem(FormattableString formattableString)
{
foreach (var arg in formattableString.GetArguments())
{
// do something to interpolation argument 'arg'
}
// use the standard interpolation and the current culture info
// to get an ordinary String:
var formatted = formattableString.ToString();
// ...
}
Call the above method with:
AddLogItem($"The foo is {foo}, and the bar is {bar}.");
For example, one could choose not to incur the performance cost of formatting the string if the
logging level was already going to filter out the log item.
Implicit conversions
There are implicit type conversions from an interpolated string:
var s = $"Foo: {foo}";
System.IFormattable s = $"Foo: {foo}";
You can also produce an IFormattable variable that allows you to convert the string with invariant
context:
var s = $"Bar: {bar}";
System.FormattableString s = $"Bar: {bar}";
Current and Invariant Culture Methods
If code analysis is turned on, interpolated strings will all produce warning CA1305 (Specify
IFormatProvider). A static method may be used to apply current culture.
public static class Culture
{
public static string Current(FormattableString formattableString)
{
return formattableString?.ToString(CultureInfo.CurrentCulture);
https://riptutorial.com/ 141

