C # 6.0, .NET 4.51 and VS2015 - Why does string interpolation work?

Having read the following:

It seemed to me that in addition to String Interpolation, any project compiled in VS2015 against .NET 4.51 could use the new features of C #.

However, I tried the following code on my dev machine using VS2015 4.51 targeting:

string varOne = "aaa"; string varTwo = $"{varOne}"; if (varTwo == "aaa") { } 

and not only did I not get a compiler error, it worked like varTwo , containing aaa , as expected.

Can someone explain why this is the way I would not expect it to work? I guess I'm missing what FortattableString really means. Can someone give me an example?

+6
source share
2 answers

As mentioned in the comments, line interpolation works in this case, since the whole new compiler does the conversion of the expression to an "equivalent string. Format call" at compile time.

From https://msdn.microsoft.com/en-us/magazine/dn879355.aspx

String interpolation is converted at compile time to invoke an equivalent string. Format the call. This leaves the localization support in place as before (although still with traditional format strings) and does not introduce any post-compiling code injection through the strings.


FormattableString is a new class that allows you to check string interpolation before rendering so you can check values ​​and protect against injection.

 // this does not require .NET 4.6 DateTime now = DateTime.Now; string s = $"Hour is {now.Hour}"; Console.WriteLine(s); //Output: Hour is 13 // this requires >= .NET 4.6 FormattableString fs = $"Hour is {now.Hour}"; Console.WriteLine(fs.Format); Console.WriteLine(fs.GetArgument(0)); //Output: Hour is {0} //13 
+12
source

Can someone explain why this is so, since I did not expect this to work?

This works because you are compiling the new Roslyn compiler that ships with VS2015 and knows how to parse the syntax sugar of string interpolation (it just causes the correct string.Format overload). If you try to use the .NET Framework 4.6 classes that work well with string interpolation, such as FormattableString or IFormattable , you will encounter a compile-time error (unless you add them yourself . See the bottom of the post).

I guess I'm missing what FormattableString really means.

FormattableString is a new type introduced in .NET 4.6 that allows you to use the new line interpolation function with the custom IFormatProvider of your choice. Since this cannot be done directly in the interpolated string, you can use FormattableString.ToString(IFormatProvider) , which can be passed in any custom format.

+7
source

All Articles