Dusted Codes

Programming adventures

Using C# 6 features in ASP.NET MVC 5 razor views

Recently I upgraded my IDE to Visual Studio 2015 and made instant use of many new C# 6 features like the nameof keyword or interpolated strings.

It worked (and compiled) perfectly fine until I started using C# 6 features in ASP.NET MVC 5 razor views:

Feature not available in C# 5 message, Image by Dustin Moris Gorski

Feature 'interpolated strings' is not available in C# 5. Please use language version 6 or greater.

The project compiles fine, but intellisense underlines my interpolated string in red and tells me that I can't use this feature in C# 5. Well I know that myself, but the real question is why does it think it is C# 5?

It is the compiler's fault

I knew I didn't have to change the .NET Framework version to .NET 4.6, because it is a language feature and not a .NET framework feature. The compiler is responsible for translating my C# 6 code into IL code which is supported by the framework.

However, saying that I don't get any errors at compilation time even though I made a lot of use of C# 6 features all over my project.

Maybe it is an intellisense bug in Visual Studio 2015? Not really, because when I start my project I get a yellow screen of death which matches the intellisense error:

Interpolated String Runtime Error in ASP.NET MVC 5, Image by Dustin Moris Gorski

ASP.NET Runtime compiler

The problem is at runtime when ASP.NET tries to compile the razor view. ASP.NET MVC 5 uses the CodeDOM Provider which doesn't support C# 6 language features.


There are two solutions to fix the problem:

  1. Upgrade your application to MVC 6 (which is still in beta at the time of writing)
  2. Reference the Roslyn compiler in your project by using the compiler element in your web.config

The 2nd option is as easy as installing the CodeDOM Providers for .NET Compiler nuget package.

It replaces the CodeDOM provider with the new .NET compiler platform (aka Roslyn) compiler as a service API. After installing the nuget package in your MVC 5 project you will be able to use C# 6 features in razor views as well!