Search code examples
c#.netvisual-studionaming-conventionsstatic-analysis

Can C#/Visual Studio naming rules be configured to flag single-letter prefixes?


The naming rule violations can be configured in VS via Tools > Options > Text Editor > C# > Code Style > Naming for camelCase and flag locals and parameters with unexpected prefixes like _IsVisible or m_Name, while allowing them for private fields.

IDE1006 Naming rule violation: Prefix 'm_' is not expected IDE1006 Naming rule violation: Prefix '_' is not expected

However, locals/parameters erroneously prefixed with m but without the underscore such as

public void Method(int mValue)
{
    bool mLocalVar = false;
}

do not get flagged.

Can the naming rules be configured to consider an m prefix without _ to be a violation as well?


Solution

  • You can create your own code analyzer.

    Create code analyzer project:

    enter image description here

    In the first analyzer project, modify the function

            public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();
    
            context.RegisterSyntaxNodeAction(AnalyzeNode, Microsoft.CodeAnalysis.CSharp.SyntaxKind.VariableDeclarator);
            context.RegisterSyntaxNodeAction(AnalyzeParameter, Microsoft.CodeAnalysis.CSharp.SyntaxKind.Parameter);
        }
    
        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var variableDeclaration = (Microsoft.CodeAnalysis.CSharp.Syntax.VariableDeclaratorSyntax)context.Node;
            var variableName = variableDeclaration.Identifier.Text;
    
            if (variableName.StartsWith("m"))
            {
                var diagnostic = Diagnostic.Create(Rule, variableDeclaration.GetLocation(), variableName);
                context.ReportDiagnostic(diagnostic);
            }
        }
        private static void AnalyzeParameter(SyntaxNodeAnalysisContext context)
        {
            var parameter = (Microsoft.CodeAnalysis.CSharp.Syntax.ParameterSyntax)context.Node;
            var parameterName = parameter.Identifier.Text;
    
            if (parameterName.StartsWith("m"))
            {
                var diagnostic = Diagnostic.Create(Rule, parameter.GetLocation(), parameterName);
                context.ReportDiagnostic(diagnostic);
            }
        }
    }
    

    Set warning or error:

    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
    

    Modify the text in resx file:

    enter image description here

    In code fix project :

    comment the fix code:

        // Register a code action that will invoke the fix.
        //context.RegisterCodeFix(
        //    CodeAction.Create(
        //        title: CodeFixResources.CodeFixTitle,
        //        createChangedSolution: c => MakeUppercaseAsync(context.Document, declaration, c),
        //        equivalenceKey: nameof(CodeFixResources.CodeFixTitle)),
        //    diagnostic);
    

    Select vsix project as start project to test:

    enter image description here