Search code examples
c#roslynanalyzer

How to make c# analyzer from CLI, to warn on usage of ! operator


Ok, as usual the msft docs are utterly useless for me. Here is my Q:

How can I make an analyzer using the CLI (dotnet 6.0 SDK on linux) and have it run when I dotnet build other projects, and have it print warnings if the null forgiveness operator (!) is used. I do NOT use visual studio. Also how can I verify analyzers are even being loaded / initialized by dotnet build.

For context, we require a __unwrap<T>() helper method, which checks at runtime that the object is indeed not null, instead of sacrificing safety. And this project here does not seem to work for me: https://github.com/tom-englert/Nullable.Extended#roslyn-analyzer


Solution

  • Using your aforementioned analyzer from nuget (for other people reading this: dotnet add package Nullable.Extended.Analyzer), you need to specify the severity of its diagnostic Ids (NX0001..3).

    There are multiple ways to do it. Feel free to follow the Global AnalyzerConfig method if you prefer, but I'm going to use the .editorconfig file for the sake of simplicity (you might already have one):

    [*.cs]
    dotnet_diagnostic.NX0001.severity=warning
    dotnet_diagnostic.NX0002.severity=warning
    dotnet_diagnostic.NX0003.severity=warning
    

    The 3 different Ids and some description can be found in the source code. You can also see there that the DiagnosticDescriptor's are created with DiagnosticSeverity.Info - which are not shown when doing a dotnet build - hence the need to manually override as warnings.