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.
Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.
To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal.
It marks the string as a verbatim string literal. In C#, a verbatim string is created using a special symbol @. @ is known as a verbatim identifier. If a string contains @ as a prefix followed by double quotes, then compiler identifies that string as a verbatim string and compile that string.
String concatenation is a little faster for a very small number of arguments, but requires more memory. After 20+ arguments concat is better by time and memory.
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}");
I finally figured this out. As it turns out, the compiler feature relies on two types, System.FormattableString
, and System.Runtime.CompilerServices.FormattableStringFactory
. These were not available for my project - I guess they might not yet have made it into all platforms for CTP6.
This apparently made the compiler hang as described. Once I pulled the code for those two types from the CoreCLR code and added it to my project, my code works as expected.
This was figured out through code comments for the InterpolationTests. Hooray for the source being available :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With