Search code examples
c#.netautomated-refactoring

Does C# offer a compile-time way to refactor code based on annotations?


I haven't written much in C# yet, primarily writing in C++, so I was wondering if C# offers a way to let you instruct the compiler to refactor code at compile-time based on an annotation?

Basically I'm looking for a way to let the compiler automatically wrap every non-blacklisted class variable in a custom wrapper class with assignment and conversion operators for the wrapped type. So instead of public CustomWrapper<int> someInt; you simply use public int someInt; as a regular integer and the compiler refactors the code if the class is annotated with the corresponding annotation.

To prevent some quick remarks, the custom wrapper is non-trivial.


Solution

  • This is not built into C# or even .NET. What you are looking for are IL rewriting tools or AOP tools. These are all applied after the code is compiled. Take a look at

    • Fody - "Extensible tool for weaving .net assemblies"
    • PostSharp - an AOP code weaver (commercial)

    Here's an article to aid you for rolling your own.

    If you must or want to do some complex refactoring prior to compiling, you can write a custom Rosyln code analyzer and corresponding code fix. This makes it semi-automatic; if you apply the suggestion as you code, the code can be transformed according to the code-fix.