Custom StyleCop rule not working as expected
- by Jon
I'm trying to write a StyleCop rule that disallows underscores anywhere. There is a rule to say that you cant have public string _myfield but I don't want underscores anywhere ie/method names, property names, method parameters.
Below is my code but its not working properly. Can anyone suggest why?
using Microsoft.StyleCop;
using Microsoft.StyleCop.CSharp;
namespace DotNetExtensions.StyleCop.Rules
{
[SourceAnalyzer(typeof(CsParser))]
public class NoUnderScores : SourceAnalyzer
{
public override void AnalyzeDocument(CodeDocument document)
{
CsDocument csdocument = (CsDocument) document;
if (csdocument.RootElement != null && !csdocument.RootElement.Generated)
csdocument.WalkDocument(new CodeWalkerElementVisitor<object>(this.VisitElement), null, null);
}
private bool VisitElement(CsElement element, CsElement parentElement, object context)
{
if (!element.Generated)
{
foreach(var token in element.Tokens)
{
if (token.Text.Contains("_"))
AddViolation(element, "NoUnderScores");
}
}
return true;
}
}
}