Specifying locale for string interpolation in C#6 (Roslyn CTP6)

driis picture driis · Mar 29, 2015 · Viewed 15.8k times · Source

String interpolation in C#6 lets me write:

decimal m = 42.0m;
string x = $"The value is {m}";

However, a very common use case for string formatting is to specify the locale used for formatting the values. Let's say I need to use InvariantCulture for the formatting operation above, what is the syntax for that ?

This discussion suggests that I should be able to do this:

string x = INV($"The value is {m}");

Where INV is defined as

public static string INV(IFormattable formattable)
{
    return formattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture);
}

However, this does not work. It compiles, but it leaves my program hanging at in cmd.exe at startup - as if klr.exe, that I assume is being invoked, hangs (Compiler bug?)

This is an ASP.NET 5 Console Project in VS15 CTP 6.

Answer

pharring picture pharring · Mar 30, 2015

What you have should work. It's the correct syntax. There's also a convenient method on the "System.FormattableString" abstract class which has the same effect as the suggested "INV" helper method.

using static System.FormattableString;
...
string x = Invariant($"The value is {m}");