Generally, new versions of the C# compiler are released at the same time as new versions of the .Net Framework. But the C# compiler does not depend on the version of the Framework you're using, instead it depends on specific types and members being present. Those types are included in the new framework, but they can also come from somewhere else.
For example, this is why you can use C# 5.0 async
-await
on .Net 4.0, using the Microsoft.Bcl.Async
package.
Specifically for C# 6.0, basic string interpolation does not require any new types or members, so it doesn't need new framework version. This code:
string s = $"pie is {3.14}";
Console.WriteLine(s);
Compiles to:
string s = string.Format("pie is {0}", 3.14);
Console.WriteLine(s);
Which works just fine on .Net 4.5.
On the other hand, one advanced feature of string interpolation is that the interpolated string can be converted to IFormattable
or FormattableString
. For example, this code:
IFormattable formattable = $"pie is {3.14}";
Console.WriteLine(formattable.ToString(null, CultureInfo.InvariantCulture));
Console.WriteLine(formattable.ToString(null, new CultureInfo("cs-CZ")));
Compiles to:
IFormattable formattable = FormattableStringFactory.Create("pie is {0}", 3.14);
Console.WriteLine(formattable.ToString(null, CultureInfo.InvariantCulture));
Console.WriteLine(formattable.ToString(null, new CultureInfo("cs-CZ")));
This compiles fine on .Net 4.6, but fails on .Net 4.5 with:
error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported
But you can make it compile by including the following code:
namespace System.Runtime.CompilerServices
{
class FormattableStringFactory
{
public static IFormattable Create(string format, params object[] args) => null;
}
}
Of course, with this dummy implementation, the following code will throw a NullReferenceException
.
You can actually make it work by referencing the unofficial StringInterpolationBridge
package.