How to suppress code analysis messages for all type members?

penartur picture penartur · Sep 2, 2015 · Viewed 16.2k times · Source

Let's say I have an enumeration of all currencies:

public enum CurrencyType
{
    /// <summary>
    /// United Arab Emirates dirham
    /// </summary>
    [EnumMember]
    AED = 784,

    /// <summary>
    /// Afghan afghani
    /// </summary>
    [EnumMember]
    AFN = 971,

    /// <summary>
    /// Albanian lek
    /// </summary>
    [EnumMember]
    ALL = 008,

    ...
}

VS 2015 code analysis keeps complaining about 100 violations of CA1709 for every individual member.

This is an useful rule by itself, and I do not want to disable it; yet it is of not much help in this specific case, as CurrencyType is public and is used in a whole lot of other projects.

I can suppress the message; however, VS only offers me to suppress it for every individual member - meaning that I'll have 100 [SuppressMessage(...)] lines, which will clutter the code.

Is there any way to suppress all CA1709 for all CurrencyType members, while not suppressing it for all other code in this project, without having to write 100 [SuppressMessage(...)]?

There is a Scope parameter of SuppressMessageAttribute, but the documentation is unclear on that one. I've tried placing both

[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "type", Justification = "Currency codes are defined in ISO standard.")]

and

[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Justification = "Currency codes are defined in ISO standard.")]

on CurrencyType itself. Neither does work.

Answer

jessehouwing picture jessehouwing · Sep 3, 2015

There is no way to suppress a rule for a whole class or enum in this case and have the suppression apply to all of its members, unfortunately.

But what you can do, is create a CodeAnalaysisDictionary.xml, add it to your project containing the Enum and setting its 'Build action' propery to CodeAnalysisDictionary:

enter image description here

Once you have set this up, you can add the abbreviations and case exceptions to the dictionary like this:

<Dictionary>
      <Acronyms>
         <CasingExceptions>
            <Acronym>AED</Acronym>
            <Acronym>AFN</Acronym>
            <Acronym>ALL</Acronym>
            <Acronym>...</Acronym>
         </CasingExceptions>
      </Acronyms>
</Dictionary>

While these exceptions will apply to any element in the code with these acronyms in them, they will prevent the CA1709 warnings from showing up.

See the documentation for more information on the exceptions you can setup using the dictionary files: