Home / Forums / Building Compile-Time Fast Enum ToString with C# Source Generators

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Source

Building Compile-Time Fast Enum ToString with C# Source Generators

SourceGenDev
C# Tooling
MEMBER
Rep: 158
Join Date: Jan 2020
Posts: 8
Thanks: 79
2y ago · Feb 19, 2024 1:30 PM
#1
Standard
CODE
myEnum.ToString()
in .NET uses reflection and allocates a new string on the heap every single call.

Generating a zero-allocation extension method at compile time with a Source Generator:

CSHARP
// What the Source Generator produces automatically:
public static class PlayerStateExtensions
{
    public static string ToStringFast(this PlayerState state) => state switch
    {
        PlayerState.Idle => nameof(PlayerState.Idle),
        PlayerState.Running => nameof(PlayerState.Running),
        PlayerState.Jumping => nameof(PlayerState.Jumping),
        PlayerState.Dead => nameof(PlayerState.Dead),
        _ => state.ToString()
    };
}


Because
CODE
nameof()
is a compile-time string literal, calling
CODE
state.ToStringFast()
returns the interned string constant with **0 heap allocations** and **O(1) switch dispatch**!
SourceGenDev · C# Tooling
Metaprogramming with C# 9+ Source Generators and Roslyn Anal...
The following users thanked SourceGenDev for this post:
ReflectPro
Reflection & Roslyn
MEMBER
Rep: 355
Join Date: Mar 2022
Posts: 9
Thanks: 75
2y ago · Feb 19, 2024 5:02 PM
#2
Source generators are the ultimate replacement for runtime reflection. FastToString and FastTryParse generated on build make enum serialization 50x faster!
ReflectPro · Reflection & Roslyn
C# source generators, Expression Trees, and runtime IL emiss...
CSharpNinja
Senior .NET Developer
VIP
Rep: 329
Join Date: Jan 2020
Posts: 16
Thanks: 75
2y ago · Feb 20, 2024 1:02 AM
#3
Check out the community
CODE
NetEscapades.EnumGenerators
package on NuGet if you don't want to write the Roslyn analyzer yourself. It does this automatically via a
CODE
[EnumExtensions]
attribute.
CSharpNinja · Senior .NET Developer
C# enthusiast, building distributed backend services and hig...