Tuesday, November 24, 2015

Find code patterns using C# and Roslyn: Introducing IntelliFind

Since the beginning of time, code editors have been equipped with ‘Find’ and / or ‘Find All’ features. This allows the user to search for any or all occurrences of literal text in a code base. Most editors also allow you to use regular expressions for more ‘advanced’ searches.

But what if you need to search for all variables with the name ‘goldCustomer’, because someone decided these need to be renamed to ‘specialCustomer’. Or search for methods with a set of tree parameters named “name”, “dateOfBirth” and "address”, because these need to be refactored to use a new Person class. Or your codebase is filled with another repeating pattern that seemed to be a good idea to someone at one point, but now hinders development big time. These kind of searches are not easily done with simple text search or regular expressions. You need a search tool that understands the syntax of your code in order to search for these kinds of patterns.

Fortunately we now have the Roslyn compiler engine that understands the structure of C# code and exposes this structure in the form of syntax trees. You can use these syntax trees to analyze code by creating custom analyzers like I did here. For ad-hoc searches in day to day work however writing a custom analyzer for one time use is just way to much work. It involves creating a new solution in a new visual studio instance, writing the code for the analyzer, debugging it in the experimental Visual Studio Instance and then install it into yet another instance in order to search your target code base. It would be nice if we could simplify this.