Custom StyleCop rule not working as expected

Posted by Jon on Stack Overflow See other posts from Stack Overflow or by Jon
Published on 2012-07-07T15:04:32Z Indexed on 2012/07/07 15:16 UTC
Read the original article Hit count: 377

Filed under:
|
|

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;
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET