I ran into this problem today while mucking around with the installed Nuget packages and web.config of an MVC 5 project where the Razor views started showing up an error while using the C# 6 String interpolation feature. There was a squiggly line under all string interpolation expressions and when I pointed to it, the error said “Cannot use C# 6 feature with C# 5”. When run, there was the dreaded YSOD (Yellow Screen Of Death for the uninitiated) that said:
CS1525: Invalid expression term ‘$’
Here’s a discussion on Stackoverflow on this topic that helped.
I had accidently uninstalled the Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget package, so Razor didn’t recognize that C# 6 should be used. The mentioned Nuget package uses Roslyn as the compiler platform.
- Install the Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget package.
- (This is required only if you don’t already have the mentioned section in Web.config) Add the following XML fragment in your root web.config
<configuration> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=188.8.131.52, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=184.108.40.206, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" /> </compilers> </system.codedom> </configuration>
After adding the DotNetCompilerPlatform package and the system.codedom section, Razor was happy with all C# 6 features being used in the views 🙂
- Rationale behind Roslyn in ASP.NET applications: Blog post by Damian Edwards
- An (official) overview of Roslyn