Search code examples
c#roslynroslyn-code-analysis

In a C# Roslyn Analyzer, can I detect if a given Diagnostic is enabled?


I'm writing a Roslyn analyzer which detects certain patterns in the code that we don't like, and raising a Diagnostic (the specifics are irrelevant here). However, detecting said patterns is potentially an expensive operation.

If a user has disabled the diagnostic using a ruleset file, using NOWARN, or other global/assembly level setting, is there a way that I can pick up on that inside my analyzer and use it in an if statement to avoid the potentially expensive parts?

I'm aware that I can put the diagnostic in it's own class SomeNewAnalyzer : DiagnosticAnalyzer, and the compiler won't run that analyzer if all diagnostics it supports are disabled, but is there way to do this as part of another Analyzer that raises multiple diagnostics?


Solution

  • There's a method in the DiagnosticDescriptor class which you can use:

    public ReportDiagnostic GetEffectiveSeverity(CompilationOptions compilationOptions);
    

    It returns ReportDiagnostic.Suppress if the rule is suppressed.

    You can get the compilation options from your analysis context like this:

    context.SemanticModel.Compilation.Options