Reader small image

You're reading from  Refactoring with C#

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781835089989
Edition1st Edition
Languages
Right arrow
Author (1)
Matt Eland
Matt Eland
author image
Matt Eland

Matt Eland is a Microsoft MVP in Artificial Intelligence (AI) who has been working with .NET since 2001. Matt has served as a senior engineer, software engineering manager, and .NET programming instructor. He is currently an AI specialist and senior consultant at Leading EDJE near Columbus, Ohio, where he helps companies with their software engineering and data science needs using C# and related technologies. Matt speaks and writes in his community and co-organizes the Central Ohio .NET Developers Group while pursuing a master's degree in data analytics.
Read more about Matt Eland

Right arrow

Creating a Roslyn Analyzer

In the previous chapter, we covered the use of code analyzers to detect issues in code. But what happens when your team has common issues that aren’t detected by any existing analysis rules?

It turns out that modern C# provides a means for building custom analyzers through something called Roslyn Analyzers. In this chapter, we’ll see how Roslyn Analyzers work in action by building an analyzer of our own.

This chapter covers the following topics:

  • Understanding Roslyn Analyzers
  • Creating a Roslyn Analyzer
  • Testing Roslyn Analyzers with RoslynTestKit
  • Sharing analyzers as Visual Studio extensions

Technical requirements

Unlike other chapters, we won’t be starting with sample code. Instead, we’ll be starting with a blank solution and gradually adding new projects to that solution.

The starting empty solution and final code for this chapter are available from GitHub at https://github.com/PacktPublishing/Refactoring-with-CSharp in the Chapter13 folder.

Understanding Roslyn Analyzers

Before we can go into what a Roslyn Analyzer is, let’s talk about Roslyn.

Roslyn is the codename for the reimagined .NET Compiler Platform that was released alongside Visual Studio 2015. Since “.NET Compiler Platform” is a lot to say, most people refer to this as the Roslyn compiler or simply Roslyn for short.

Before Roslyn, if a tool wanted to understand C#, VB, or F# source code, developers needed to write their own language parser for these code files. This involved a significant amount of time and complexity, and this effort needed to be repeated every time these programming languages changed. This led to tools being slower to support new language features, lost productivity, and bugs.

One of the explicit goals of the Rosyln compiler was to provide visibility into the structure of code in a standardized way. This way, plugins could work with the Roslyn APIs to get live information about code without having to write their...

Creating a Roslyn Analyzer

People create custom Roslyn Analyzers when they experience common issues in their code that no existing analyzer addresses. These custom analyzers help enforce rules that specific organizations or teams find to be useful. However, these organization-specific rules tend to be less relevant to the larger .NET community.

Here are a few examples of when you might want to build a custom analyzer:

  • Your team has been having issues with too many FormatException errors from things such as int.Parse and wants to make int.TryParse their standard
  • Due to large files and limited memory, your team wants to avoid the File.ReadAllText method and use stream-based approaches instead
  • Your team mandates that all classes must override the ToString method to improve the debugging and logging experience

Note that none of these approaches relate to styling or syntax. Instead, these analyzers deal with team-specific decisions about how to best use .NET. We...

Testing Roslyn Analyzers with RoslynTestKit

We’ll show how to use your Roslyn Analyzers in projects of your own at the end of this chapter, but we’ll start by writing unit tests around our existing analyzer.

At a high level, we want to test two things with our analyzer:

  • The analyzer doesn’t trigger for code that doesn’t violate its rule.
  • The analyzer correctly flags code that it should.

We’ll do this with two unit tests in a new unit test project.

Adding a Roslyn Analyzer test project

Our tests can be written in MSTest, xUnit, or NUnit. We’ll use xUnit for consistency.

We’ll start by adding a new xUnit project to the solution by right-clicking on the solution and then choosing Add and then New Project…, as we’ve done before.

After this, select the C# version of xUnit Test Project and click Next. Name your project Packt.Analyzers.Tests and click Next. When prompted with the framework, select...

Sharing analyzers as Visual Studio extensions

Once you’re ready to try an analyzer on more code or share it with your peers, there are a few options available:

  • Deploy the analyzer as a NuGet package, as we’ll discuss in the next chapter
  • Create a Visual Studio Installer (VSIX) to install the analyzers locally
  • Create a new project and add an explicit reference to the analyzers by editing the .csproj file and adding an Analyzer node, as shown here:
<ItemGroup>
  <Analyzer Include="..\some\path\Your.Analyzer.dll" />
</ItemGroup>

This last approach is one you might consider if you had a large solution and wanted your analyzer to only apply to other projects in that solution. However, I’ve found this approach to be buggy and require frequent reloads of Visual Studio for changes in the analyzers to take hold, so we’ll use the VSIX approach as we close out this chapter.

Creating a Visual Studio extension...

Summary

In this chapter, we created our first Roslyn Analyzer, tested it with RoslynTestKit, and built a VSIX extension to integrate it into Visual Studio.

We saw how Roslyn Analyzers power all the warnings we interact with in Visual Studio and how you and your team can create new Roslyn Analyzers to detect and flag issues that are unique to your team and its codebase.

In the next chapter, we’ll see how Roslyn Analyzers can be used to fix the issues they find and help safely refactor your code.

Questions

  1. How do Roslyn Analyzers work?
  2. When would you want to create your own Roslyn Analyzer?
  3. How can you verify that Roslyn Analyzers work correctly?

Further reading

You can find more information about the topics that were covered in this chapter at these URLs:

Here are some popular open-source Roslyn Analyzers on GitHub:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Refactoring with C#
Published in: Nov 2023Publisher: PacktISBN-13: 9781835089989
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Matt Eland

Matt Eland is a Microsoft MVP in Artificial Intelligence (AI) who has been working with .NET since 2001. Matt has served as a senior engineer, software engineering manager, and .NET programming instructor. He is currently an AI specialist and senior consultant at Leading EDJE near Columbus, Ohio, where he helps companies with their software engineering and data science needs using C# and related technologies. Matt speaks and writes in his community and co-organizes the Central Ohio .NET Developers Group while pursuing a master's degree in data analytics.
Read more about Matt Eland