NetEscapades.EnumGenerators 1.0.0-beta18

This is a prerelease version of NetEscapades.EnumGenerators.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package NetEscapades.EnumGenerators --version 1.0.0-beta18
                    
NuGet\Install-Package NetEscapades.EnumGenerators -Version 1.0.0-beta18
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta18" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NetEscapades.EnumGenerators" Version="1.0.0-beta18" />
                    
Directory.Packages.props
<PackageReference Include="NetEscapades.EnumGenerators" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NetEscapades.EnumGenerators --version 1.0.0-beta18
                    
#r "nuget: NetEscapades.EnumGenerators, 1.0.0-beta18"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NetEscapades.EnumGenerators@1.0.0-beta18
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NetEscapades.EnumGenerators&version=1.0.0-beta18&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=NetEscapades.EnumGenerators&version=1.0.0-beta18&prerelease
                    
Install as a Cake Tool

alternate text is missing from this package README image NetEscapades.EnumGenerators

Build status NuGet

NetEscapades.EnumGenerators requires the .NET 7 SDK or higher. NetEscapades.EnumGenerators.Interceptors requires the .NET 8.0.400 SDK or higher. You can still target earlier frameworks like .NET Core 3.1 etc, the version requirement only applies to the version of the .NET SDK installed.

Why use these packages?

Many methods that work with enums are surprisingly slow. Calling ToString() or HasFlag() on an enum seems like it should be fast, but it often isn't. This package provides a set of extension methods, such as ToStringFast() or HasFlagFast() that are designed to be very fast, with fewer allocations.

For example, the following benchmark shows the advantage of calling ToStringFast() over ToString():

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1348 (20H2/October2020Update)
Intel Core i7-7500U CPU 2.70GHz (Kaby Lake), 1 CPU, 4 logical and 2 physical cores
  DefaultJob : .NET Framework 4.8 (4.8.4420.0), X64 RyuJIT
.NET SDK=6.0.100
  DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
Method FX Mean Error StdDev Ratio Gen 0 Allocated
ToString net48 578.276 ns 3.3109 ns 3.0970 ns 1.000 0.0458 96 B
ToStringFast net48 3.091 ns 0.0567 ns 0.0443 ns 0.005 - -
ToString net6.0 17.985 ns 0.1230 ns 0.1151 ns 1.000 0.0115 24 B
ToStringFast net6.0 0.121 ns 0.0225 ns 0.0199 ns 0.007 - -
ToString net10.0 6.4389 ns 0.1038 ns 0.0971 ns 0.004 1.000 24 B
ToStringFast net10.0 0.0050 ns 0.0202 ns 0.0189 ns 0.001 - -

Enabling these additional extension methods is as simple as adding an attribute to your enum:

[EnumExtensions] // 👈 Add this
public enum Color
{
    Red = 0,
    Blue = 1,
}

The main downside to the extension methods generated by NetEscapades.EnumGenerators is that you have to remember to use them. The NetEscapades.EnumGenerators.Interceptors package solves this problem by intercepting calls to ToString() and replacing them with calls ToStringFast() automatically using the .NET compiler feature called interceptors.

For example, imagine you have this code, which uses the Color enum defined above:

var choice = Color.Red;
Console.WriteLine("You chose: " + choice.ToString());

By default you need to manually replace these ToString() calls with ToStringFast(). However, when you use the NetEscapades.EnumGenerators.Interceptors, the interceptor automatically replaces the call to choice.ToString() at compile-time with a call to ToStringFast(), as though you wrote the following:

// The compiler replaces the call with this 👇 
Console.WriteLine("You chose: " + choice.ToStringFast());

There are many caveats to this behaviour, as described below, but any explicit calls to ToString() or HasFlag() on a supported enum are replaced automatically.

Adding NetEscapades.EnumGenerators to your project

Add the package to your application using

dotnet add package NetEscapades.EnumGenerators

This adds a <PackageReference> to your project:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
  </PropertyGroup>

  
  <PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta18" />
  

</Project>

Adding the package will automatically add a marker attribute, [EnumExtensions], to your project.

To use the generator, add the [EnumExtensions] attribute to an enum. For example:

[EnumExtensions]
public enum MyEnum
{
    First,

    [Display(Name = "2nd")]
    Second,
}

This will generate a class called MyEnumExtensions (by default), which contains a number of helper methods. For example:

public static partial class MyEnumExtensions
{
    public const int Length = 2;

    public static string ToStringFast(this MyEnum value, bool useMetadataAttributes)
        => useMetadataAttributes ? value.ToStringFastWithMetadata() : value.ToStringFast();

    public static string ToStringFast(this MyEnum value)
        => value switch
        {
            MyEnum.First => nameof(MyEnum.First),
            MyEnum.Second => nameof(MyEnum.Second),
            _ => value.ToString(),
        };

    private static string ToStringFastWithMetadata(this MyEnum value)
        => value switch
        {
            MyEnum.First => nameof(MyEnum.First),
            MyEnum.Second => "2nd",
            _ => value.ToString(),
        };

    public static bool IsDefined(MyEnum value)
        => value switch
        {
            MyEnum.First => true,
            MyEnum.Second => true,
            _ => false,
        };

    public static bool IsDefined(string name) => IsDefined(name, allowMatchingMetadataAttribute: false);

    public static bool IsDefined(string name, bool allowMatchingMetadataAttribute)
    {
        var isDefinedInDisplayAttribute = false;
        if (allowMatchingMetadataAttribute)
        {
            isDefinedInDisplayAttribute = name switch
            {
                "2nd" => true,
                _ => false,
            };
        }

        if (isDefinedInDisplayAttribute)
        {
            return true;
        }

        
        return name switch
        {
            nameof(MyEnum.First) => true,
            nameof(MyEnum.Second) => true,
            _ => false,
        };
    }

    public static MyEnum Parse(string? name)
        => TryParse(name, out var value, false, false) ? value : ThrowValueNotFound(name);

    public static MyEnum Parse(string? name, bool ignoreCase)
        => TryParse(name, out var value, ignoreCase, false) ? value : ThrowValueNotFound(name);

    public static MyEnum Parse(string? name, bool ignoreCase, bool allowMatchingMetadataAttribute)
        => TryParse(name, out var value, ignoreCase, allowMatchingMetadataAttribute) ? value : throw new ArgumentException($"Requested value '{name}' was not found.");

    public static bool TryParse(string? name, out MyEnum value)
        => TryParse(name, out value, false, false);

    public static bool TryParse(string? name, out MyEnum value, bool ignoreCase) 
        => TryParse(name, out value, ignoreCase, false);

    public static bool TryParse(string? name, out MyEnum value, bool ignoreCase, bool allowMatchingMetadataAttribute)
        => ignoreCase
            ? TryParseIgnoreCase(name, out value, allowMatchingMetadataAttribute)
            : TryParseWithCase(name, out value, allowMatchingMetadataAttribute);

    private static bool TryParseIgnoreCase(string? name, out MyEnum value, bool allowMatchingMetadataAttribute)
    {
        if (allowMatchingMetadataAttribute)
        {
            switch (name)
            {
                case string s when s.Equals("2nd", System.StringComparison.OrdinalIgnoreCase):
                    value = MyEnum.Second;
                    return true;
                default:
                    break;
            };
        }

        switch (name)
        {
            case string s when s.Equals(nameof(MyEnum.First), System.StringComparison.OrdinalIgnoreCase):
                value = MyEnum.First;
                return true;
            case string s when s.Equals(nameof(MyEnum.Second), System.StringComparison.OrdinalIgnoreCase):
                value = MyEnum.Second;
                return true;
            case string s when int.TryParse(name, out var val):
                value = (MyEnum)val;
                return true;
            default:
                value = default;
                return false;
        }
    }

    private static bool TryParseWithCase(string? name, out MyEnum value, bool allowMatchingMetadataAttribute)
    {
        if (allowMatchingMetadataAttribute)
        {
            switch (name)
            {
                case "2nd":
                    value = MyEnum.Second;
                    return true;
                default:
                    break;
            };
        }

        switch (name)
        {
            case nameof(MyEnum.First):
                value = MyEnum.First;
                return true;
            case nameof(MyEnum.Second):
                value = MyEnum.Second;
                return true;
            case string s when int.TryParse(name, out var val):
                value = (MyEnum)val;
                return true;
            default:
                value = default;
                return false;
        }
    }

    public static MyEnum[] GetValues()
    {
        return new[]
        {
            MyEnum.First,
            MyEnum.Second,
        };
    }

    public static string[] GetNames()
    {
        return new[]
        {
            nameof(MyEnum.First),
            nameof(MyEnum.Second),
        };
    }
}

If you create a "Flags" enum by decorating it with the [Flags] attribute, an additional method is created, which provides a bitwise alternative to the Enum.HasFlag(flag) method:

public static bool HasFlagFast(this MyEnum value, MyEnum flag)
    => flag == 0 ? true : (value & flag) == flag;

Note that if you provide a [EnumMember] attribute, the value you provide for this attribute can be used by methods like ToStringFast() and TryParse() by passing the argument useMetadataAttributes: true. Alternatively, you can use the [Display] or [Description] attributes, and set the MetadataSource property on the [EnumExtensions] attribute e.g.

[EnumExtensions(MetadataSource = MetadataSource.DisplayAttribute)]
public enum EnumWithDisplayNameInNamespace
{
    First = 0,
    [Display(Name = "2nd")]
    Second = 1,
    Third = 2,
}

Alternatively, you can use MetadataSource.None to choose none of the metadata attributes. In this case, the overloads that take a useMetadataAttributes parameter will not be emitted.

You can set the default metadata source to use for a whole project by setting the EnumGenerator_EnumMetadataSource property in your project:

<PropertyGroup>
  <EnumGenerator_EnumMetadataSource>EnumMemberAttribute</EnumGenerator_EnumMetadataSource>
</PropertyGroup>

You can override the name of the extension class by setting ExtensionClassName in the attribute and/or the namespace of the class by setting ExtensionClassNamespace. By default, the class will be public if the enum is public, otherwise it will be internal.

Usage Analyzers

NetEscapades.EnumGenerators includes optional analyzers that encourage the use of the generated extension methods instead of the built-in System.Enum methods. These analyzers can help improve performance by suggesting the faster, generated, alternatives like ToStringFast(), HasFlagFast(), and TryParse().

Enabling the analyzers

The usage analyzers are disabled by default. To enable them, set the EnumGenerator_EnableUsageAnalyzers MSBuild property to true in your project:

<PropertyGroup>
  <EnumGenerator_EnableUsageAnalyzers>true</EnumGenerator_EnableUsageAnalyzers>
</PropertyGroup>

Alternatively, add a .globalconfig file to your project with the following content:

is_global = true
build_property.EnumGenerator_EnableUsageAnalyzers = true

After using one of these configuration options, the analyzers in your project should be enabled with the default severity of Warning.

Configuring analyzer severity (optional)

Once enabled, you can optionally configure the severity of individual analyzer rules using one or more .editorconfig files. For example, the following changes all the built-in analyzers to report usages as errors instead of warnings

[*.{cs,vb}]

# NEEG004: Use ToStringFast() instead of ToString()
dotnet_diagnostic.NEEG004.severity = error

# NEEG005: Use HasFlagFast() instead of HasFlag()
dotnet_diagnostic.NEEG005.severity = error

# NEEG006: Use generated IsDefined() instead of Enum.IsDefined()
dotnet_diagnostic.NEEG006.severity = error

# NEEG007: Use generated Parse() instead of Enum.Parse()
dotnet_diagnostic.NEEG007.severity = error

# NEEG008: Use generated GetNames() instead of Enum.GetNames()
dotnet_diagnostic.NEEG008.severity = error

# NEEG009: Use generated GetValues() instead of Enum.GetValues()
dotnet_diagnostic.NEEG009.severity = error

# NEEG010: Use generated GetValuesAsUnderlyingType() instead of Enum.GetValuesAsUnderlyingType()
dotnet_diagnostic.NEEG010.severity = error

# NEEG011: Use generated TryParse() instead of Enum.TryParse()
dotnet_diagnostic.NEEG011.severity = error

These are reported in both your IDE and via the CLI as Roslyn errors:

Demonstrating the Roslyn errors shown for using the non-generated methods

Valid severity values include: none, silent, suggestion, warning, and error.

Code fixes

All usage analyzers include automatic code fixes. When a diagnostic is triggered, you can use the quick fix functionality in your IDE to automatically replace the System.Enum method with the corresponding generated extension method:

Demonstrating the code-fix option available in your IDE for each of the analyzers

Enabling automatic interception

Interceptors were introduced as an experimental feature in C#12 with .NET 8. They allow a source generator to "intercept" certain method calls, and replace the call with a different one. NetEscapades.EnumGenerators has support for intercepting ToString() and HasFlag() method calls.

To use interceptors, you must be using at least version 8.0.400 of the .NET SDK. This ships with Visual Studio version 17.11, so you will need at least that version or higher.

To use interception, add the additional NuGet package NetEscapades.EnumGenerators.Interceptors to your project using:

dotnet add package NetEscapades.EnumGenerators.Interceptors

This adds a <PackageReference> to your project. You can additionally mark the package as PrivateAssets="all" and ExcludeAssets="runtime", similarly to NetEscapades.EnumGenerators.

By default, adding NetEscapades.EnumGenerators.Interceptors to a project enables interception for all enums defined in that project that use the [EnumExtensions] or [EnumExtensions<T>] attributes. If you wish to intercept calls made to enums with extensions defined in other projects, you must add the [Interceptable<T>] attribute in the project where you want the interception to happen, e.g.

[assembly:Interceptable<DateTimeKind>]
[assembly:Interceptable<Color>]

If you don't want a specific enum to be intercepted, you can set the IsInterceptable property to false, e.g.

[EnumExtensions(IsInterceptable = false)]
public enum Colour
{
    Red = 0,
    Blue = 1,
}

Interception only works when the target type is unambiguously an interceptable enum, so it won't work

  • When ToString() is called in other source generated code.
  • When ToString() is called in already-compiled code.
  • If the ToString() call is implicit (for example in string interpolation)
  • If the ToString() call is made on a base type, such as System.Enum or object
  • If the ToString() call is made on a generic type

For example:

// All the examples in this method CAN be intercepted
public void CanIntercept()
{
    var ok1 = Color.Red.ToString(); // ✅
    var red = Color.Red;
    var ok2 = red.ToString(); // ✅
    var ok3 = "The colour is " + red.ToString(); // ✅
    var ok4 = $"The colour is {red.ToString()}"; // ✅
}

// The examples in this method can NOT be intercepted
public void CantIntercept()
{
    var bad1 = ((System.Enum)Color.Red).ToString(); // ❌ Base type
    var bad2 = ((object)Color.Red).ToString(); // ❌ Base type
    
    var bad3 = "The colour is " + red; // ❌ implicit
    var bad4 = $"The colour is {red}"; // ❌ implicit

    string Write<T>(T val)
        where T : Enum
    {
        return val.ToString(); // ❌ generic
    }
}

Preserving usages of the [EnumExtensions] attribute

The [EnumExtensions] attribute is decorated with the [Conditional] attribute, so their usage will not appear in the build output of your project. If you use reflection at runtime on one of your enums, you will not find [EnumExtensions] in the list of custom attributes. If you wish to preserve these attributes in the build output, you can define the NETESCAPADES_ENUMGENERATORS_USAGES MSBuild variable.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    
    <DefineConstants>$(DefineConstants);NETESCAPADES_ENUMGENERATORS_USAGES</DefineConstants>
  </PropertyGroup>

  
  <PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta18" />
</Project>
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net451 is compatible.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages (9)

Showing the top 5 NuGet packages that depend on NetEscapades.EnumGenerators:

Package Downloads
DSharpPlus

A C# API for Discord based off DiscordSharp, but rewritten to fit the API standards.

Indrivo.FileStorage.Accessor.Contracts

Package Description

NetEscapades.EnumGenerators.Interceptors

A source generator interceptor for automatically intercepting calls to ToString() on enums, and replacing them with calls to ToStringFast() generated from NetEscapades.EnumGenerators

Magelon-png.PixivApi

Pixiv Web Api

apex.net-Entities

Models for apex.net

GitHub repositories (6)

Showing the top 6 popular GitHub repositories that depend on NetEscapades.EnumGenerators:

Repository Stars
Nexus-Mods/NexusMods.App
Home of the development of the Nexus Mods App
DSharpPlus/DSharpPlus
A .NET library for making bots using the Discord API.
xin9le/FastEnum
The world fastest enum utilities for C#/.NET
SteveDunn/Intellenum
Intelligent Enums
Altinn/altinn-studio
Next generation open source Altinn platform and applications.
Kengxxiao/CelestiteLauncher
Cross platform third-party DMM Game Player in C#
Version Downloads Last Updated
1.0.0-beta21 12,070 3/9/2026
1.0.0-beta20 35,753 1/15/2026
1.0.0-beta19 6,971 1/5/2026
1.0.0-beta18 238 1/5/2026
1.0.0-beta16 28,098 11/4/2025
1.0.0-beta14 113,826 6/15/2025
1.0.0-beta13 35,778 5/12/2025
1.0.0-beta12 185,808 1/26/2025
1.0.0-beta11 151,926 10/24/2024
1.0.0-beta09 288,031 5/15/2024
1.0.0-beta08 233,051 6/5/2023
1.0.0-beta07 137,181 3/10/2023
1.0.0-beta06 36,894 12/20/2022
1.0.0-beta05 449 12/19/2022
1.0.0-beta04 215,794 11/30/2021
1.0.0-beta03 2,065 11/26/2021
1.0.0-beta02 388 11/22/2021
1.0.0-beta01 632 11/18/2021

### Breaking Changes

* Add support for generating `ReadOnlySpan<char>` based methods when System.Memory is present (#182, #212)

### Features

* Add support for disabling number parsing using `EnumParseOptions` (#175)
* Add support for automatic `ToLowerInvariant` and `ToUpperInvariant` in `ToStringFast()`, using `SerializationOptions` (#177)
* Add Analyzers to encourage using the generated methods
 * Add analyzer to detect ToString() on enums with [EnumExtensions] or EnumExtensions<T> (#196)
 * Extend ToStringAnalyzer to detect enum usage in string interpolation (#198)
 * Add analyzer to detect HasFlag() and suggest HasFlagFast() replacement (#199)
 * Extract the extension class and namespace in analyzers (#200)
 * Add using directive support to HasFlagAnalyzer and ToStringAnalyzer code fixes (#202)
 * Add analyzer for Enum.IsDefined() suggesting generated IsDefined method (#203)
 * Add analyzer for Enum.Parse() suggesting generated Parse method (NEEG007) (#204)
 * Add analyzer for Enum.GetNames() with generated alternative (#209)
 * Add analyzer for Enum.GetValues() with code fix to use generated method (#207)
 * Add analyzer for Enum.GetValuesAsUnderlyingType() usage (#208)
 * Add analyzer for Enum.TryParse() usage (#206)
 * Refactor analyzers to reduce some duplication (#205)
 * Disable usage analyzers by default, enable via editorconfig (#214)
 * Update default severity to warning (#218)
 * Change how the usage analyzers are enabled to use an `EnumGenerator_EnableUsageAnalyzers` MSBuild property instead (#222)
 * Add AnalyzerTests project to confirm that the analyzers are actually triggering warnings in a real project (#223)
 * Mention globalconfig in the docs, and tweak the detection for consistency (#224)

### Fixes

* Remove ToStringFastWithMetadata when it's not needed for perf reasons(#176)
* Minor performance fixes in generated code (#178)
* Use Collection expressions in generated code if possible (#179)

### Misc

* Build tweaks (#180)
* Add support for .NET 10.0 in Benchmark project (#184) Thanks [@HakamFostok](https://github.com/HakamFostok)!
* Add Usage Analyzers documentation to README (#216)
* Update Readme (#219)


See https://github.com/andrewlock/NetEscapades.EnumGenerators/blob/main/CHANGELOG.md#v100-beta18 for more details.