Nick Albrecht Nick Albrecht -4 years ago 527
C# Question

Using C# 7 features inside of a View in an ASP.NET MVC Core project

I've looked for other questions related to this, but none seem to be quite what I'm looking for.

I have a website running on ASP.NET Core with the new project structure in VS2017. Code files using C#7 features compile fine. But attempting to use those features in a View results in a series of errors about syntax. I tried installing Roslyn to get it to be used when compiling views since from what I can tell the C#7 features are available in the Roslyn nuget package 2.x and higher. But now I'm getting feedback that explicitly says

error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7 or greater.

In the past I'd check the web.config, but there is no web.config in an ASP.NET Core project other than the nearly empty one at the root for handling the request off from IIS.

How do I indicate that my Views should be compiled with Roslyn since that isn't done until runtime? At least I'm assuming that would fix my problem at this point.

That question is not a duplicate of this, as I mentioned at the start, I've also looked for existing questions. That's specifically enabling C#7 features in your app at compile time, and only for an ASP.NET application. I'm using ASP.NET Core, which does not have a web.config with any compilation settings defined in it. Also, what I'm trying to do it for the Views which are compiled at runtime and may be on a different system.


For anyone interested, You have to add Roslyn to your project (which I knew), but you also have to configure the
to use
that indicate the language version (default is 6). I had done this but I didn't do it correctly. I needed to assign the result of
back overtop of the
to replace them.

services.AddMvc().AddRazorOptions(options => options.ParseOptions = options.ParseOptions.WithLanguageVersion(LanguageVersion.CSharp7));

Answer Source

Could you try the following (recommended by folks on the ASP.NET core team):

  1. Install the Microsoft.CodeAnalysis.CSharp (version 2.0.0) and System.ValueTuple (version 4.3.0) packages
  2. In Startup.cs, in the ConfigureServices method, configure Razor to use C# 7 by doing the following: services.AddMvc().AddRazorOptions(options =>     options.ParseOptions = new CSharpParseOptions(LanguageVersion.CSharp7));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download