I am looking for a way to suppress individual violation messages at the method or class level created by StyleCop.
To provide a simple example of what I'm looking for..
// Attribute will suppress all occurrences of violation "SA1306"
// within the Testing1() method.
[SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1306:FieldNamesMustBeginWithLowerCaseLetter",
Justification = "Reviewed. Suppression is OK here.")]
public void Testing1()
{
//Fires off SA1306
var Temp = "";
//Also fires off SA1306
var Temp2 = "";
}
With the above, I'm wondering if there's a way to suppress the first violation, but still have the second reported.
I have searched and found a few related questions, but I'd like to know for certain if this is possible to do or not.
Thanks.
Before StyleCop logs a rule violation, it performs a check to see if the violation should be suppressed. It does this by checking whether a suppression is specified on the element (that is causing the violation) or any of its parents (e.g., a class would be a parent of a method, a method would be the parent of a variable declaration element in method). That means that two distinct violations inside a method would be suppressed by the suppression on the method itself.
The key here is how it searches for the matching element and what elements are searched. The following method is in CsParser.cs, within the CSharperParser project of the source:
private static bool MatchElementWithPossibleElementsTraversingParents(CsElement element, IList<CsElement> possibleElements)
{
Param.AssertNotNull(element, "element");
Param.AssertNotNull(possibleElements, "possibleElements");
// Loop through each possible element using a for-style loop rather than a foreach, since this
// is faster and this method is called very often.
for (int i = 0; i < possibleElements.Count; ++i)
{
CsElement possibleMatch = possibleElements[i];
// Walk through the element and each of its parents to see if any is a match.
CsElement item = element;
while (item != null)
{
if (item == possibleMatch)
{
return true;
}
item = item.FindParentElement();
}
}
return false;
}
Backing up a bit to understand the context, the parameter CsElement element will be the parent element of a parsed token where a violation has been detected and possibleElements is a list of CsElements that are tied to a suppression rule. Every element that comes through this method will match an enum of "ElementType" used by stylecop. A few example element types are class, field, constructor and using directive where one of these element types will be tied to the violation in question.
In the example I listed in my question, this is effectively what happens;
Hence, both violations are suppressed by the same suppression attribute, so the answer to my question is ultimately no.