Creating Roslyn Analyzers

Nick Lydon
2 min readFeb 11, 2025

--

It’s surprisingly easy to harness dotnet’s metaprogramming capabilities, since the compiler has been made available as a service. Teams can now define what they consider to be an error, for example:

  1. using an internal API incorrectly
  2. doing something questionable with the language itself
  3. requiring an attribute to be applied to certain classes, etc.

Whilst the core libraries are very good, unfortunately the tooling around it needs improvement. I recently created a semantic analyzer and it was difficult to find the tools and guides listed in a single place.

Tools

  • RoslynQuoter
    This invaluable website allows you to insert “source” C# code that you want to reproduce. The output is the method calls that will ultimately create that syntax tree for you and then eventually emit a string of source code. You don’t need to know all the names for the tokens, keywords, etc. that represent your code — instead you write what you want to see and then let it work that out for you. This is incredibly useful for creating source generators or code fixes.
  • Visual Studio Roslyn Syntax Visualizer
    For users of VSCode and Rider: I’m afraid you may have to download Visual Studio for this as I haven’t been able to find a similar working extension for these other IDEs. Given a source file in your project, this window shows you the syntax tree for it, allowing you to drill down to see how it is parsed. This is useful for writing analyzers that detect improper usage of APIs/the language, etc.

Articles

  • Release Tracking Analyzer
    This is something you want to consider when including analyzers as a distributable package so that consumers know what has been updated with each release. It will be included by default when creating a new analyzer project using the template in Rider.
  • Meziantou’s Writing a Roslyn analyzer
    A very extensive guide to working with Roslyn, that importantly includes unit testing and how to reference an analyzer project from within its own solution, rather than consuming a nuget package.

--

--

Nick Lydon
Nick Lydon

Written by Nick Lydon

British software developer working as a freelancer in Berlin. Mainly dotnet, but happy to try new things! https://github.com/NickLydon

No responses yet