Analyzing Indexers using Roslyn

Sep 28, 2015

I've occasionally come across code that just really bothers me. One such case that I have seen is the abuse of indexers. I have seen some programmers use this as a "free" method call that doesn't require a name. They load it up with parameters and it just doesn't feel right. For example, some code that looks like this:

This code is perfectly legal C#, but can be very confusing for someone coming into the code for the first time. Let's create an analyzer that raises a diagnostic any time there is more than one parameter to the indexer to mitigate the creation of this monstrosity. To start, we'll register a SyntaxNodeAction forSyntaxKind.IndexerDeclaration` nodes.

As you can see, once you know how to create an analyzer, you can easily create them to ensure the code you and your team are writing follow certain standards. You can also start creating a suite of standards that you like to follow to ensure you don't fall into any bad habits.