A lot of C# 9-related content is around. Very often, records are mentioned as one of the most interestning new features. So, while we can find A LOT of buzz around them, I wanted to provide a distilled set of facts typically not presented when describing them.
Fact #1. You can use them in pre-.NET 5
Records has been announced as C# 9 feature (and thus .NET 5), and it is the officially supported way. But you can “not officialy” use most C# 9 features in earlier frameworks, as they don’t need the new runtime support. So, if being not “officially supported” does not bother you too much, just set proper LangVersion in csproj and you are (almost) done:
|
<PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <LangVersion>9</LangVersion> </PropertyGroup> |
Trying to compile super typical example like the following:
|
public record Person { public string FirstName { get; init; } public string LastName { get; init; } } |
will still not compile, complaining about the lack of mysterious IsExternalInit type:
|
Error CS0518 Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported |
To be funny, the workaround is just to define it in your project (exactly as it is in the newer CoreLib, shipped with .NET 5):
|
namespace System.Runtime.CompilerServices { public class IsExternalInit{} } |
BTW, IsExternalInit is not required for the record usage by itself, but for init as discussed in https://github.com/dotnet/runtime/issues/34978 and https://github.com/dotnet/runtime/pull/37763. So if creating mutable records is ok, no need for that.
Sidenote: If you are interested what more you can “not officially” use, look at Using C# 9 outside .NET 5 #47701 discussion.Continue reading