Member-only story
C# code quality tooling with Roslyn, Resharper and NDepend
Recently, I was investigating some options for (automated) code quality tooling, including code metrics, dependency graphs, and self-imposed coding styles. In order to have a maintainable, scalable and tidy solution, these are very important aspects to keep track of.
In this article, I would like to highlight three approaches, starting from simple to sophisticated.
Native VS approaches
Let’s start with something simple. If you’re just looking to add some basic warnings to your code, the most approachable and simplest way is right within your code VS allows a lot of customization when it comes to errors and warnings. The most basic ways to do this is by adding a #warning directive in your code, or by abusing the [Obsolete] attribute, which is a compiler supported attribute to generate special warnings.
#warning Warn me about this
DoSomething();[Obsolete("Warning two")]
static void DoSomething(){ }
This code will end up in the warnings & error view like this.
As you can see, this is pretty clunky & specific, but it might just be good enough to get to where you want to. Note that you can also raise warnings to errors in your .csproj files, see the respective properties here.
Another creative and simple idea to ensure coding guidelines is through Reflection and unit tests. Imagine you want to ensure that assembly X does not contain references to specific other assemblies.
For this, you can write a simple unit test loading the assembly, and checking the references assemblies within. If you detect an invalid reference, your test will fail, and the code change will not be permitted.
In a similar fashion, you could also checking naming of properties / methods / fields, etc. on specific types through reflection, to ensure naming standards.
These are all some simple yet often good enough ideas of how you can get some basic checks in place with minimal effort.
Source analyzers
After this small detour, let's now get into the proper tooling. If you want to have warnings and errors for custom triggers beyond the default warnings and errors available, let’s say for a team-specific coding standard you run with, you might want to write a custom roslyn analyzer to detect it.