Multi-targeting a Roslyn analyzer

  • Gérald Barré

This post is part of the series 'Roslyn Analyzers'. Be sure to check out the rest of the blog posts of the series!

A Roslyn Analyzer must target .NET Standard 2.0. However, you may want to target a more recent framework such as .NET 5.0 to take advantage of the Nullable Reference Types. While Nullable Reference Types work with libraries targeting .NET Standard 2.0, older targets cannot take advantage of the framework annotations. So, you'll get lots of meaningless warnings. You can read my previous post for more details.

The idea is to build both targets and only include the .NET Standard 2.0 DLL into the published package. The final NuGet package content should look like this:

csproj (MSBuild project file)
<Project Sdk="Microsoft.NET.Sdk">
    <!-- Multi-target the library. Must contain at least "netstandard2.0" -->

    <!-- -->

    <!-- Do not include the dll into the NuGet package, we'll add it manually at the right location -->

    <!-- Include the netstandard2.0 DLL into the package -->
    <None Include="$(OutputPath)\netstandard2.0\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />

  <!-- 👇 disable the nullable warnings when compiling for .NET Standard 2.0 -->
  <PropertyGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">

    <PackageReference Include="Microsoft.CodeAnalysis" Version="3.8.0" />

You can now use the .NET CLI to build the package:

dotnet pack --configuration Release

Et voilà!

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub