Search code examples
c#stylecop

how to get style cop to ignore a specific instance of a violation


I have a few instances in my code where Style cop gives out that:

"SA1119: The line contains unnecessary parenthesis."

Now I totally agree with this if I have a line of code that says:

int someValue = (((12 + 3) + 5));

However when I have something more complicated like:

textXpos = ((((float)this.Width - imageoffset) - textsize.Width) / 2);

I understand that I can rewrite this like:

textXpos = (((float)this.Width - imageoffset - textsize.Width) / 2);

And It will evaluate out to the same values, but I find the first one easier to read. Is there a way to tell styecop to ignore this instance of the error?

Or do I need to work around this by assigning some of the equation to temp variables?

I don't want to wrap this code in an autogenerated region as I do want style cop to evaluate this section of code.

Thanks


Based on the suggestion by ken2k I tried the following:

using System.Diagnostics.CodeAnalysis;

. . .

[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1119:StatementMustNotUseUnnecessaryParenthesis", Justification = "Better for readability.")]
    public int Testmethod()
    {
        int returnValue = (((5 - 5) - 5) / 2);
        return returnValue;
    }

But this doesn't seem to have any effect? Am I missing something?



Solution

  • You can add the following statement before the header of your method:

    [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1119:StatementMustNotUseUnnecessaryParenthesis", Justification = "Better for readability.")]
    

    But warnings SA1119 will be ignored for the whole method.

    EDIT: at least remove the first and last parenthesis:

    textXpos = (((float)this.Width - imageoffset) - textsize.Width) / 2;