Harmful collection transformations. Part 2: automatic diagnostics

Published on Wednesday, October 13, 2021

The previous post contains code examples that can be simplified by removing ToArray() or ToCharArray() calls. And an interesting example with List<char> constructor. But we need to be very attentive to find such places in our code. It would be much safer to do it automatically. This post shows us about automatic compiler diagnostics that can detect issues.

Analyzers

Since the release of the new .NET compiler platform Roslyn developers have got powerful tools for code analysis. Roslyn compilers offer APIs for C# and Visual Basic that we can use for code-related applications. One of the possible applications is code analyzer, that produces warnings and can offer an automatic code fix in IDE.

One of the most popular analyzers built on Roslyn is ConfigureAwaitChecker.Analyzer. The analyzer helps to find awaited methods without ConfigureAwait(false) call and offers automatic code fix.

Collections.Analyzer

Collections.Analyzer is a set of roslyn-based diagnostics for C#-projects that detect potential issues with different collections and produce warnings.

Installation

Every analyzer can be installed as a usual nuget-package. Just add a package reference to a project:

<PackageReference Include="Collections.Analyzer" Version="0.1.9" />

The analyzer will work only in the project it was added to. If you want to analyse all projects in your solution, you can add file Directory.build.props to the solution directory with content:

<Project>
  <ItemGroup>
    <PackageReference Include="Collections.Analyzer" Version="0.1.9" />
  </ItemGroup>
</Project>

MSBuild will read these properties.

Build

If your code has problems, you'll see warnings as usual.

PS C:\example> dotnet build
C:\example\App\Program.cs(12,31): warning CI0001: Redundant string conversion [C:\example\App\App.csproj]
C:\example\App\Program.cs(17,21): warning CI0001: Redundant string conversion [C:\example\App\App.csproj]
  App -> C:\example\App\bin\Debug\net472\App.exe

    Warnings: 2
    Errors: 0

CI0001: Redundant string conversion is a new diagnostic described in the Collections.Analyzer package.

IDE

Besides compiler warnings all diagnostics are integrated in IDE (Visual Studio or Rider) with automatic code fixes. So, we can correct our code on the fly. Let's see how it works for strings.

LINQ

String ToCharArray

foreach statement

String ToCharArray

List<char> constructor

The case with List<char> constructor is very seldom and specific, but analyzer always helps us:

String ToCharArray

LINQ on method

Analyzer works on methods that return strings:

String ToCharArray

These are the most popular string-to-array issues that I have encountered. But if you have any ideas feel free to write to me or add them to github issues.

In the next article we will continue to look at other collections, possible issues and add automatic diagnostics if it's possible.

Links