In Visual Studio 2015, the new C# and VB .NET compilers are based on the .NET Compiler Platform known as Roslyn. This allows third-party tools to use the compiler itself to query the structure of code, rather than having to redo the compiler’s job. It also provides the ability to fix the code by modifying its structure.
You can use the NuGet Package Manager in VS2015 to install analyzers. At the moment there are very few available, and they’re still prerelease software. For this demonstration we’ll use the CodeCracker C# analyzer:
Once you install the package, you’ll see that the analyzer has been added under a special Analyzers node under the References in Solution Explorer. If you expand the analyzer, you can see all the rules that it enforces:
As you can see, the code analysis rules may be enforced at various levels. Those marked as errors will result in actual compiler errors, and obviously cause the build to fail.
The rules that are broken by the code will then show up in the error list, which in VS2015 has been enhanced so that you can see more info about the error/rule and also click on the error code link to go to its online documentation (at the time of writing this article, the CodeCracker’s error code links are broken):
The best thing about live static code analysis is that they’re live: the rules will be checked as you’re writing your code, and you don’t even need to build for them to be evaulated.
Warnings may be sorted out by moving the caret within the relevant code and pressing Ctrl+. (Control Dot), after which the Quick Actions become available. See, code analyzers don’t need to limit themselves to complaining. If a fix is available, you’ll have the option to apply it, and you can preview the changes as with any other refactoring:
If you know better than the code analyzer, you can opt to suppress the warning instead:
Code analysis allows rules to be enforced on your team’s code. Roslyn facilitates this by making it easy to plug in different code analyzers (and hopefully in future there will be a wider range to choose from) and by running code analysis live, without the need to build the project.
Note: this demonstration used the CodeCracker C# analyzer in order to show the different levels of rules (e.g. warnings, errors, etc), since the StyleCop analyzer’s rules are all warnings. The CodeCracker C# analyzer is in quite a mess at the time of writing, with missing fixes, broken rule documentation links, and countless grammatical errors. But it’s prerelease, so we’ll pretend that’s a good excuse and forgive it for its sins.