Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrading Microsoft.CodeAnalysis.CSharp for Roslyn analyzer

Tags:

c#

roslyn

nuget

I'm working on a Roslyn C# analyzer, and need to use the RecordDeclarationSyntax type from newer versions of the Microsoft.CodeAnalysis.CSharp nuget package from 3.3.1 to 4.2.0. Unfortunately, it seems that if I upgrade the package alone, I get the following compile error:

error NU1605: Detected package downgrade: Microsoft.CodeAnalysis.Analyzers from 3.3.3 to 2.9.8. Reference the package directly from the project to select a different version.

This makes sense, since the Microsoft.CodeAnalysis.Analyzers version should have the version corresponding with the Microsoft.CodeAnalysis.CSharp release.

If I upgrade both packages (Microsoft.CodeAnalysis.CSharp to 4.2.0 and Microsoft.CodeAnalysis.Analyzers to 3.3.3), the solution compiles, but the analyzer fails to run.

Is there any way that I can use the latest Microsoft.CodeAnalysis.CSharp APIs within an analyzer?

like image 724
Thomas Woltjer Avatar asked Oct 20 '25 08:10

Thomas Woltjer


1 Answers

Be mindful when updating the version of the Roslyn packages, because it's a tooling breaking change: greater versions of Roslyn require greater versions of the .NET SDK / Visual Studio (which ships with a .NET SDK in-box) as a consumer. Have a look at the compatibility of the Roslyn NuGet packages.

If you publish your .NET Analyzers publicly (e.g. via NuGet.org), I suggest targeting the lowest version of Roslyn necessary (where the respective major version of the .NET SDK is still supported) for the widest range of compatibility:

When you just need the C# 9.0 RecordDeclarationSyntax, then prefer targeting Microsoft.CodeAnalysis.CSharp 3.8.0, which requires the .NET SDK 5.0.100 / Visual Studio 2019 v16.8.0. When you also require the C# 10 ClassOrStructKeyword on record, then prefer targeting Microsoft.CodeAnalysis.CSharp 4.0.1, which requires the .NET 6 SDK 6.0.100 / Visual Studio 2022 v17.0.0.

If you publish and consume your .NET Analyzers within a controlled environment (e.g. within your organization), then I guess targeting the latest version of Roslyn is fair, with the requirement of keeping the .NET SDK / Visual Studio also up to date.

like image 153
FlashOver Avatar answered Oct 21 '25 21:10

FlashOver