Search code examples
c#visual-studio-2015roslynanalyzerroslyn-code-analysis

Configure ordering rule in StyleCop Analyzers to enforce user-defined member order


Is it possible to configure the StyleCop Analyzers so that "my" order of members within a class (which deviates from what SA1201 describes) can be checked? Namely I want to have my properties above the constructor whereas SA1201 requires them to be placed below the contructor. I do not want to disable the ordering rule because I do want to stick with having the order being checked.


Solution

  • The following just presents the basic idea, but one should really consider looking at what StyleCop-Analyzers do.

    Using on the Analyzer with Code Fix (NuGet + VSIX) project template I came up with a first draft of an analyzer that is capable of detecting when properties are placed after methods. The implementation of the static AnalyzeSymbol method (which is generated on project creation) in the DiagnosticAnalyzer.cs file to achieve this is:

    private static void AnalyzeSymbol(SymbolAnalysisContext context)
    {
      var members = namedTypeSymbol.GetMembers();
      var methods = from m in members
                    where (m.Kind == SymbolKind.Method && 
                      !m.IsImplicitlyDeclared && m.CanBeReferencedByName)
                    select m;
    
      var properties = from m in members
                       where m.Kind == SymbolKind.Property
                       select m;
    
      foreach (var p in properties)
      {
        foreach (var m in methods)
        {
          if (p.Locations.First().SourceSpan.Start > m.Locations.First().SourceSpan.Start)
          {
             // For all such symbols, produce a diagnostic.
             var diagnostic = Diagnostic.Create(Rule, m.Locations[0], m.Name);
             context.ReportDiagnostic(diagnostic);
          }
        }
      }
    }