C#6.0 have a string interpolation - a nice feature to format strings like:
var name = \"John\";
WriteLine($\"My name is {name}\");
The ex
String interpolation is difficult to combine with localization because the compiler prefers to translate it to string.Format(...), which does not support localization. However, there is a trick that makes it possible to combine localization and string interpolation; it is described near the end of this article.
Normally string interpolation is translated to
string.Format, whose behavior cannot be customized. However, in much the same way as lambda methods sometimes become expression trees, the compiler will switch fromstring.FormattoFormattableStringFactory.Create(a .NET 4.6 method) if the target method accepts aSystem.FormattableStringobject.The problem is, the compiler prefers to call
string.Formatif possible, so if there were an overload ofLocalized()that acceptedFormattableString, it would not work with string interpolation because the C# compiler would simply ignore it [because there is an overload that accepts a plain string]. Actually, it's worse than that: the compiler also refuses to useFormattableStringwhen calling an extension method.It can work if you use a non-extension method. For example:
static class Loca { public static string lize(this FormattableString message) { return message.Format.Localized(message.GetArguments()); } }Then you can use it like this:
public class Program { public static void Main(string[] args) { Localize.UseResourceManager(Resources.ResourceManager); var name = "Dave"; Console.WriteLine(Loca.lize($"Hello, {name}")); } }It's important to realize that the compiler converts the
$"..."string into an old-fashioned format string. So in this example,Loca.lizeactually receives"Hello, {0}"as the format string, not"Hello, {name}".