How to Use C# 9 in Xamarin.Forms Projects Today
September 29, 2020
.NET 5 is around the corner. It brings a plethora of
good stuff, but what makes me excited the most are the new C# features: records and more advanced pattern matching.
The record
keyword facilitates the usage of immutable state, and I really wanted to use it.
But no matter what I’ve tried, setting TFM to .NET 5 didn’t work for me on Mac. No worries, as it turned out C# 9 can be used today with .NET Standard projects!
Here’s how:
- Switch Visual Studio for Mac to Preview channel
- Create a new Xamarin.Forms project
-
In the library project change the TFM to
.NETStandard2.1
, language version to 9:<TargetFramework>netstandard2.1</TargetFramework> <LangVersion>9</LangVersion>
-
Add the following code:
// Without this dummy class C#9's records won't compile namespace System.Runtime.CompilerServices { public static class IsExternalInit { } }
YMMV, but it works on my machine with the following configuration:
- macOS Catalina 10.15.6
- Xcode 12.0
- Visual Studio Community for Mac 8.8 Preview (8.8 build 2120)
- Mono 6.12.0.93
- Roslyn 3.8.0-2.20414.4
- .NET Core SDK 3.1.402
- Xamarin.iOS 13.22.1.23
- Xamarin.Android 11.1.0.3
Alas, Rider 2020.3 EAP 1 chokes on record
s. VSfM and VS Code are fine with it.
Enjoy.