Search code examples
.netfxcop

How to detect an auto-implemented property in a custom FxCop rule?


I'm trying to write a rule for DTOs, that only allows auto-implemented properties. How do you detect that a property is auto-implemented using the FxCop API?


Solution

  • Actually there is a difference between auto-properties and properties implemented by user in the IL compiled code. Auto-properties setters and getters are tagged with System.Runtime.CompilerServices.CompilerGeneratedAttribute.

    Auto properties compiled IL code

    Hence with the tool NDepend, where you can write custom code queries and custom code rules through C# LINQ queries, matching auto-properties getters and setters is just a matter of writing the LINQ query:

    from m in Application.Methods
    where (m.IsPropertyGetter|| m.IsPropertySetter)
        && m.IsGeneratedByCompiler
    select m
    

    NDepend auto-properties code query matching

    Notice in the screenshot above that you might match getters and setters in Resources generated classes, to prevent this you can add a clause like && !m.ParentType.IsUsing("System.Resources.ResourceManager"):

    NDepend auto-properties code query matching without resources matching

    Of course, all this can be adapted to FxCop custom ruling system.

    Disclamer: I work for NDepend