Use C# 9 records in non-net5.0 projects
The new C# 9 records syntax is quite nice:
1
[DebuggerDisplay("{Name} = {Value}")]
2
record ResourceValue(string Name, string Value, bool HasFormat)
3
{
4
public bool IsIndexed { get; init; }
5
public List<string> Format { get; } = new List<string>();
6
}
Copied!
When using it in a non-net5.0 project (i.e. netstandard2.0), compilation fails with an error:
1
Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported
Copied!
To workaround the issue, simply declare the missing type in your project:
1
// Licensed to the .NET Foundation under one or more agreements.
2
// The .NET Foundation licenses this file to you under the MIT license.
3
// See the LICENSE file in the project root for more information.
4
5
using System.ComponentModel;
6
7
namespace System.Runtime.CompilerServices
8
{
9
/// <summary>
10
/// Reserved to be used by the compiler for tracking metadata.
11
/// This class should not be used by developers in source code.
12
/// </summary>
13
[EditorBrowsable(EditorBrowsableState.Never)]
14
sealed class IsExternalInit
15
{
16
}
17
}
Copied!
(as seen elsewhere too). Note the class doesn't even need to be public.
If you're multitargeting net5.0 and other TFMs, just add this bit of MSBuild to remove it for net5.0 since it's built-in:
1
<ItemGroup>
2
<Compile Remove="IsExternalInit.cs" Condition="'$(TargetFramework)' == 'net5.0'" />
3
</ItemGroup>
Copied!
Last modified 1mo ago
Copy link