C# Source Generators to boost performance in .NET 5

A new C# compiler feature that inspects code and generates additional source files promises to improve performance in a number of scenarios

C# Source Generators to boost performance in .NET 5
Thinkstock

Microsoft has introduced a preview of a C# compiler capability called Source Generators that can inspect a program and generate source files that can be added to a compilation. Microsoft says Source Generators can improve performance in a number of scenarios.

Introduced April 29, a Source Generator is a piece of code (a .NET Standard 2.0 assembly) that runs during compilation and can inspect a program to produce additional files that are compiled together with the rest of the code.

Source Generators let C# developers do the following:

  • Retrieve a compilation representing all user code being compiled. This object can be inspected and developers can write code that works with the syntax and semantic models for code being compiled, like with analyzers.
  • Generate C# source files to be added to a compilation object during compilation, with additional source code provided as input while code is being compiled.

Microsoft said user code can be inspected along with rich metadata that the compiler builds up during compilation, with C# code emitted back into the same compilation based on the data analyzed. Source Generators are akin to the Roslyn Analyzers that inspect C# or Visual Basic code, serving as analyzers that can emit C# source code.  

Source Generators are to be shipped as part of C# 9. The company has made a Source Generators Cookbook and a Source Generators design document available to help developers get started.

Scenarios that benefit from Source Generators include:

  • To perform runtime reflection. By analyzing code when an app starts up, for example, a controller discovery phase could happen at compile time, resulting in faster startup times.
  • To obviate the use of “stringly typed” APIs, such as how ASP.NET Core routing between controllers and Razor pages works. Routing could be strongly typed and the necessary strings generated as a compile-time detail.
  • To help remove barriers to linker-based and ahead-of-time compilation optimizations.

To access Source Generators, developers must install the latest .NET 5 preview and the latest Visual Studio preview

Copyright © 2020 IDG Communications, Inc.