DEV Community

loading...
.NET

Enabling C# 9 in Xamarin & .NET Standard Projects

jamesmontemagno profile image James Montemagno Originally published at montemagno.com on ・2 min read

Whoa! .NET 5 is out and C# 9 is out! This means you are ready to use records, new pattern matching, and more! But wait a second... your apps haven't been upgraded to .NET 5 yet or are a project type that don't support .NET so you don't have access to the new C# 9 features :( Or do you!?!?!?! Yes, of course you do! Most new features in C# are compiler based and not necessarily runtime based. When you create a new project the compiler determines a default C# language based on these rules:

Target framework version C# language version default
.NET 5.x C# 9.0
.NET Core 3.x C# 8.0
.NET Core 2.x C# 7.3
.NET Standard 2.1 C# 8.0
.NET Standard 2.0 C# 7.3
.NET Standard 1.x C# 7.3
.NET Framework all C# 7.3

So, if you are using .NET Standard 2.0 (the default for Xamarin.Forms) you only have access to C# 7.3 by default, which is sad. However, you can override the default inside of the .csproj. Simply open it up and add the property group:

<PropertyGroup>
   <LangVersion>preview</LangVersion>
</PropertyGroup>
Enter fullscreen mode Exit fullscreen mode

You can also pick the specific version of C# that you would like:

<PropertyGroup>
   <LangVersion>9.0</LangVersion>
</PropertyGroup>
Enter fullscreen mode Exit fullscreen mode

Now you are ready to start using C# 9 and convert all those classes over to records... almost! I say almost because there is one quirk with enabling C# 9 in non-.NET 5 project and when you use a record you will be granted with a System.Runtime.CompilerServices.IsExternalInit is no defined or imported error.

This can easily be fixed by adding the following code into any file. I like to add it into the AssemblyInfo.cs file:

namespace System.Runtime.CompilerServices
{
    public class IsExternalInit { }
}
Enter fullscreen mode Exit fullscreen mode

There you go! now you can start using all those new fancy features!! Checkout these docs:

Discussion

pic
Editor guide
Collapse
sirseanofloxley profile image
Sean Allin Newell

What happens if you hack record support in a netstandard 2.0 lib and use it in something like a net core 2.1 web api?

Collapse
jamesmontemagno profile image
James Montemagno Author

Should work just fine, it is just a compiler thing.