Search code examples
c#stylecop

Is there an option to deactivate style cop rule without making an "GlobalSuppressions.cs" file?


We use StyleCop Analyzer in our project. One of my tasks is to deactivate a few rules, but without creating a GlobalSuppressions.cs file.

I found solutions, but only with creating this file, so I'm confused.


Solution

  • To suppress a warning outside of GlobalSuppressions.cs, you can either:

    Use comments (remember to restore the warnings out of the scope!)

    #pragma warning disable IDE0052 // Remove unread private members
    private readonly Object _obj;
    #pragma warning restore IDE0052 // Remove unread private members
    

    or use the SuppressMessage attribute in place

    [SuppressMessage("Code Quality", "IDE0052:Remove unread private members", Justification = "<Pending>")]
    private readonly Object _obj;
    

    If you want to disable them globally, you can use an .editorconfig file at the root of your solution.

    root = true
    [*.{cs,vb}]
    dotnet_diagnostic.IDE0052.severity = none
    

    You can also configure a Ruleset file, but this is now deprecated.

    In your csproj:

    <PropertyGroup>
        <CodeAnalysisRuleSet>File.ruleset</CodeAnalysisRuleSet>
    </PropertyGroup>
    

    and then create File.ruleset as your per your need. It looks roughly like

    <?xml version="1.0" encoding="utf-8"?>
    <RuleSet Name="Microsoft Managed Recommended Rules" Description="These rules focus on the most critical problems in your code, including potential security holes, application crashes, and other important logic and design errors. It is recommended to include this rule set in any custom rule set you create for your projects." ToolsVersion="10.0">
      <Rules AnalyzerId="Microsoft.CodeQuality.Analyzers" RuleNamespace="Microsoft.CodeQuality.Analyzers">
        <Rule Id="CA1056" Action="None" />
      </Rules>
      </Rules>
    </RuleSet>
    

    More details at https://learn.microsoft.com/en-us/visualstudio/code-quality/use-roslyn-analyzers?view=vs-2019#rule-sets