How to suppress a StyleCop warning?

C#.NetVisual Studio-2010Stylecop

C# Problem Overview


I'm using StyleCop and want to suppress some warning which does not suit my style. I prefer to have solution for

  1. in-line code suppressing
  2. global setting suppressing

I've searched the internet but still not sure how to do the suppressing.

For method 1), They said to add the lines:

> [assembly: SuppressMessage("Microsoft.Design", "SA1202:All private methods must be placed after all public methods", Scope = "namespace", Target = "Consus.Client.ClientVaultModule.Services.OnlineDetection")]

But they do not say where and which namespace to be used.

For method 2), they said to use GlobalSuppress file but it seems not easy to search for a how-to do it at the moment.

Please help.

[Edited] In my case, I have the warning about SA1202: All private methods must be placed after all public methods which is bothering since I group my related codes into regions. I want to suppress those warning for just some certain methods.

C# Solutions


Solution 1 - C#

Here's what you need:

[SuppressMessage("Microsoft.StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess")]

Solution 2 - C#

An example of inline suppression would be similar to this - examine the namespaces in the code compared to the suppression

namespace Soapi
{
        ///<summary>
        ///</summary>
        ///<param name = "message"></param>
        ///<param name = "statusCode"></param>
        ///<param name = "innerException"></param>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)")]
        public ApiException(string message, ErrorCode statusCode, Exception innerException)
            : base(String.Format("{0}\r\nStatusCode:{1}", message, statusCode), innerException)
        {
            this.statusCode = statusCode;
        }

A global supression file is a file in the root of your project named GlobalSuppressions.cs and might look like this:

// This file is used by Code Analysis to maintain SuppressMessage 
// attributes that are applied to this project. 
// Project-level suppressions either have no target or are given 
// a specific target and scoped to a namespace, type, member, etc. 
//
// To add a suppression to this file, right-click the message in the 
// Error List, point to "Suppress Message(s)", and click 
// "In Project Suppression File". 
// You do not need to add suppressions to this file manually. 

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)", Scope = "member", Target = "Soapi.ApiException.#.ctor(System.String,Soapi.ErrorCode,System.String,System.Exception)")]

And you can generate this code automatically by right-clicking on the warning.

Solution 3 - C#

Starting with StyleCop 4.3.2, it is possible to suppress the reporting of rule violations by adding suppression attributes within the source code.

Rule Suppressions http://stylecop.soyuz5.com/Suppressions.html

but it says -

Global Suppressions

> StyleCop does not support the notion of global suppressions or > file-level suppressions. Suppressions must be placed on a code > element.

Solution 4 - C#

If you've installed StyleCop, you can right-click your project and there will be a StyleCop option. Click this and you'll see you can prevent certain rules from even running against your project. Moreover, you can create a separate rules file to share between different projects. This means you can configure the rules once the way you want them and then share that configuration between all your projects.

For individual overrides, SuppressMessage is the way to go.

Solution 5 - C#

Read the admonition from Style Cop, looking for the alphanumeric code. In your case 'SA1202'. Then browse to the corresponding page on the Style Cop website. Change the URL as appropriate https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1202.md

Copy the line labelled 'How to Suppress Violations'. Paste the attribute above the class about which Style Cop moans

[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Reviewed.")]

Solution 6 - C#

  1. Go to Solution Explorer

  2. Go to your project

  3. Expand references

  4. Expand Analyzers

  5. Expand StyleCop.Analyzers

  6. Right click on a particular rule which you want to disable at a global (project) level

  7. Set Rule Set severity -> Select None

Solution 7 - C#

Cant you just remove the rule instead of soiling your code?

Same goes for FxCop...

Solution 8 - C#

In your case, correct SuppressMessage attribute should like like the following:

[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess")]
private void SomeMethod()
{
}

Note that you can place it on any other element (e.g, on the class - then all similar violations in the entire class will be supressed).

I also agree that it's quite unobvious what to write in these fields.

Actually, the first one should be the fully qualified name of StyleCop analyser class and could be found from the source code (e.g. from here). The second one should start with rule code, then colon and the name of the rule enumeration (luckily, it always looks like the rule name displayed in the Settings Editor, but with no whitespaces).

Regarding suppressing rules "globally" - why don't just turn them off via Settings Editor? Settings files are inherited through the file system, so you could easily have one "main" settings file at the "top" of your folder structure, and some other files (holding the "difference" from main) with exceptions made for some projects, if you want so (like described here).

Good luck!

Solution 9 - C#

You can disable the rules you don't want in Settings.StyleCop file, which is in the project root folder. You will need the namespace that contains the rule, which can be found here: http://stylecop.soyuz5.com/StyleCop%20Rules.html

Settings.stylecop file code for your reference:

<StyleCopSettings Version="105">
  <Analyzers>
    <Analyzer AnalyzerId="StyleCop.CSharp.LayoutRules">
      <Rules>
        <Rule Name="ElementsMustBeSeparatedByBlankLine">
          <RuleSettings>
            <BooleanProperty Name="Enabled">False</BooleanProperty>
          </RuleSettings>
        </Rule>
      </Rules>
      <AnalyzerSettings />
    </Analyzer>
  </Analyzers>
</StyleCopSettings>

Solution 10 - C#

Alternatively you could move the code in regions into partial classes. Then the issue with the stylecop rule will go away.

Solution 11 - C#

In addition to the helpful answers already in place:

If you suppress a warning in the suppression file GlobalSuppressions.cs, you can edit that [assembly: SuppressMessage(StyleCop...blabla line and entirely remove the Scope=... and Target=... tags. That makes the suppression global in the project.

Solution 12 - C#

The README.md for the StyleCop.Analyzers NuGet package used by Visual Studio 2015+ contains a link to the documentation for the rules. The documentation for each rule contains a "How to suppress violations" section. For the SA1202 rule, the options are:

[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Reviewed.")]

and

#pragma warning disable SA1202 // ElementsMustBeOrderedByAccess
#pragma warning restore SA1202 // ElementsMustBeOrderedByAccess

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNam G VUView Question on Stackoverflow
Solution 1 - C#Jason AllorView Answer on Stackoverflow
Solution 2 - C#Sky SandersView Answer on Stackoverflow
Solution 3 - C#akjoshiView Answer on Stackoverflow
Solution 4 - C#Kent BoogaartView Answer on Stackoverflow
Solution 5 - C#Colonel PanicView Answer on Stackoverflow
Solution 6 - C#AkshunyaView Answer on Stackoverflow
Solution 7 - C#leppieView Answer on Stackoverflow
Solution 8 - C#Oleg ShuruevView Answer on Stackoverflow
Solution 9 - C#Ashwini PatilView Answer on Stackoverflow
Solution 10 - C#Philip SmithView Answer on Stackoverflow
Solution 11 - C#Stefan BormannView Answer on Stackoverflow
Solution 12 - C#Ryan PrechelView Answer on Stackoverflow