[12 December 2014 – Update 1] Upon setting up a new VM I realized that I missed a prerequisite when writing this post. The Visual Studio 2015 Preview SDK is also required. This extension includes the VSIX project subtype required by the Diagnostic and Code Fix template used for the example. I’ve included a note about installing the SDK in the prerequisites section below.
[12 December 2014 – Update 2] The github project has moved under the .NET Analyzers organization. This organization is collecting diagnostics, code fixes, and refactorings like to showcase the capabilities of this technology. The project link has been updated accordingly.
Over the past several years, Microsoft has been hard at work on the .NET Compiler Platform (formerly Roslyn). Shipping with Visual Studio 2015 the .NET Compiler Platform includes a complete rewrite of the C# and Visual Basic compilers intended to bring features that developers have come to expect from modern compilers. In addition to the shiny new compilers the .NET Compiler Platform introduces a rich set of APIs that we can harness to build custom code diagnostic analyzers and code fix providers thus allowing us to detect and correct issues in our code.
When trying to decide on a useful demonstration for these features I thought of one of my coding pet peeves: using an if..else statement to conditionally set a variable or return a value. I prefer treating these scenarios as an expression via the conditional (ternary) operator and I often find myself refactoring these patterns in legacy code. It certainly would be nice to automate that process. It turns out that this is exactly the type of task at which diagnostic analyzers and code fix providers excel and we’ll walk through the process of creating such components in this post. (more…)