The new string interpolation style in Visual Studio 2015 is this:
Dim s = $"Hello {name}"
But if I use this the code analysis tells me I break CA1305: Specify IFormatProvider
In the old times I did it like this:
Dim s = String.Format(Globalization.CultureInfo.InvariantCulture, "Hello {0}", name)
But how can it be done with the new style?
I have to mention that I'm looking for a solution for .Net 4.5.2 (for .Net 4.6 dcastro has the answer)
You'd use the
System.FormattableString
orSystem.IFormattable
class:You need to be compiling against Framework 4.6, as the
IFormattable
andFormattableString
are classes which do not exist in older versions. So if you're targeting older versions of the .NET framework you can't use the interpolation syntax without triggering the error.Unless you apply a little hack (adapted to compile against 4.6 RTM from Jon Skeet's gist and forked to my own account.). Just add a class file to your project containing:
Or if you want to achieve the same thing without adding an additional assembly to your product add the following code to your project:
See:
I have found a Nuget-Package that covers the code that jessehouwing presented in his answer.
The Nuget package 'StringInterpolationBridge' (source) adds this code to every project.
If you're targeting the .NET Framework 4.6, you can take advantage of the fact that string interpolations are implicitly convertible to
FormattableString
:From Customizing string interpolation in C# 6 by Thomas Levesque
Microsoft has made it easier to use string interpolation and comply with CA1305: Specify IFormatProvider.
If you are using C# 6 or later, you have access to the
using static
directive.In addition, the static method
FormattableString.Invariant
is available for .NET Standard 1.3, .NET Core 1.0 and .NET Framework 4.6 and later. Putting the two together allows you to do this:If, however, your goal is for the interpolation to be done via the current culture, then a companion static method
FormattableString.CurrentCulture
is proposed in .NET Core 3.0 (currently, Preview 5):