String interpolation doesn't work with .NET Framework 4.6

ぃ、小莉子 提交于 2019-11-28 11:53:15

String interpolation is a C# 6.0 feature, not one of .NET Framework 4.6. VS 2013 doesn't support C# 6 but VS 2015 does.

String interpolation is indeed a C# 6.0 feature, but C# 6 isn't limited to VS2015.

You can compile applications that leverage C# 6.0 language features in VS2013 by targeting the Roslyn compiler platform via the Microsoft.Net.Compilers NuGet package.

My experience has been that, after this package is installed, error messages during compilation can be a little misleading. If you have compile errors that are not C# 6 related, you will be shown those error messages plus error messages regarding invalid syntax relating to any C# 6 features you've used despite the fact that you're now targeting a compiler that supports them.

For instance...

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";
        var example = $"{ViewBag.Title}";
        ImASyntaxErrorWhatAmIWheresMySemicolonLOL
        return View();
    }
} 

will result in 4 error messages during compilation:

Error 1 Unexpected character '$'

Error 2 Invalid expression term ''

Error 3 ; expected

Error 4 ; expected

The first 3 errors here relate to the line that uses string interpolation, only the last ; expected error is a problem. Remove the offending line right before we return the View and the string interpolation compile errors disappear and all is well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!