Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

c#-6.0

After reading the following:

  • CLR Needed for C# 6.0
  • Does C# 6.0 work for .NET 4.0

it seemed to me that aside from String Interpolation any project I compiled in VS2015 against .NET 4.51 could use the new C# language features.

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

string varOne = "aaa";

string varTwo = $"{varOne}";

if (varTwo == "aaa")
{

}

and not only did I not receive a compiler error, it worked as varTwo contained aaa as expected.

Can someone explain why this is the case as I would not have expected this to work? I am guessing I am missing what FormattableString really means. Can someone give me an example?

like image 235
TheEdge Avatar asked Oct 21 '15 00:10

TheEdge


2 Answers

As mentioned in the comments, string interpolation works in this case as all the new compiler does is convert the expression into an "equivalent string.Format call" at compile time.

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

String interpolation is transformed at compile time to invoke an equivalent string.Format call. This leaves in place support for localization as before (though still with traditional format strings) and doesn’t introduce any post compile injection of code via strings.


The FormattableString is a new class allows you to inspect the string interpolation before rendering so you can check the values and protect against injection attacks.

// 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
like image 73
codersl Avatar answered Nov 06 '22 06:11

codersl


Can someone explain why this is the case as I would not have expected this to work?

This works since you're compiling with the new Roslyn compiler which ships with VS2015, and knows how to parse the string interpolation syntactic sugar (it simply calls the proper overload of string.Format). If you'd try to take advantage of .NET Framework 4.6 classes that work nicely with string interpolation, such as FormattableString or IFormattable, you'd run into a compile time error (unless you add them yourself. See bottom part of the post).

I am guessing I am missing what FormattableString really means.

FormattableString is a new type introduced in .NET 4.6, which allows you to use the new string interpolation feature with a custom IFormatProvider of your choice. Since this can't be done directly on the interpolated string, you can take advantage of FormattableString.ToString(IFormatProvider) which can be passed any custom format.

like image 34
Yuval Itzchakov Avatar answered Nov 06 '22 06:11

Yuval Itzchakov