NetEscapades.EnumGenerators
1.0.0-beta12
dotnet add package NetEscapades.EnumGenerators --version 1.0.0-beta12
NuGet\Install-Package NetEscapades.EnumGenerators -Version 1.0.0-beta12
<PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta12" />
paket add NetEscapades.EnumGenerators --version 1.0.0-beta12
#r "nuget: NetEscapades.EnumGenerators, 1.0.0-beta12"
// Install NetEscapades.EnumGenerators as a Cake Addin #addin nuget:?package=NetEscapades.EnumGenerators&version=1.0.0-beta12&prerelease // Install NetEscapades.EnumGenerators as a Cake Tool #tool nuget:?package=NetEscapades.EnumGenerators&version=1.0.0-beta12&prerelease
NetEscapades.EnumGenerators
- NetEscapades.EnumGenerators is a source generator package that generates extension methods for enums, to allow fast "reflection".
- NetEscapades.EnumGenerators.Interceptors is a source generator interceptor for intercepting calls to
ToString()
on enums, and automatically replacing them with calls toToStringFast()
generated by NetEscapades.EnumGenerators.
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 | - | - |
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. You can additionally mark the package as PrivateAssets="all"
and ExcludeAssets="runtime"
.
Setting
PrivateAssets="all"
means any projects referencing this one won't get a reference to the NetEscapades.EnumGenerators package. SettingExcludeAssets="runtime"
ensures the NetEscapades.EnumGenerators.Attributes.dll file is not copied to your build output (it is not required at runtime).
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta12"
PrivateAssets="all" ExcludeAssets="runtime" />
</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 [Display]
or [Description]
attribute, the value you provide for this attribute can be used by methods like ToStringFast()
and TryParse()
by passing the argument allowMatchingMetadataAttribute: true
. Adding both attributes to an enum member is not supported, though conventionally the "first" attribute will be used.
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.
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 instring
interpolation) - If the
ToString()
call is made on a base type, such asSystem.Enum
orobject
- 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
}
}
Embedding the attributes in your project
By default, the [EnumExtensions]
attributes referenced in your application are contained in an external dll. It is also possible to embed the attributes directly in your project, so they appear in the dll when your project is built. If you wish to do this, you must do two things:
- Define the MSBuild constant
NETESCAPADES_ENUMGENERATORS_EMBED_ATTRIBUTES
. This ensures the attributes are embedded in your project - Add
compile
to the list of excluded assets in your<PackageReference>
element. This ensures the attributes in your project are referenced, instead of the NetEscapades.EnumGenerators.Attributes.dll library.
Your project file should look something like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<DefineConstants>$(DefineConstants);NETESCAPADES_ENUMGENERATORS_EMBED_ATTRIBUTES</DefineConstants>
</PropertyGroup>
<PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta12"
PrivateAssets="all"
ExcludeAssets="compile;runtime" />
</Project>
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 enum
s, 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. Note that this means your project will have a runtime-dependency on NetEscapades.EnumGenerators.Attributes.dll so you need to ensure this is included in your build output.
<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-beta12" PrivateAssets="all" />
</Project>
Error CS0436 and [InternalsVisibleTo]
In the latest version of NetEscapades.EnumGenerators, you should not experience error CS0436 by default.
In previous versions of the NetEscapades.EnumGenerators generator, the [EnumExtensions]
attributes were added to your compilation as internal
attributes by default. If you added the source generator package to multiple projects, and used the [InternalsVisibleTo]
attribute, you could experience errors when you build:
warning CS0436: The type 'EnumExtensionsAttribute' in 'NetEscapades.EnumGenerators\NetEscapades.EnumGenerators\EnumExtensionsAttribute.cs' conflicts with the imported type 'EnumExtensionsAttribute' in 'MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
In the latest version of NetEscapades.EnumGenerators, the attributes are not embedded by default, so you should not experience this problem. If you see this error, compare your installation to the examples in the installation guide.
Product | Versions 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. |
.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. |
-
.NETStandard 2.0
- No dependencies.
NuGet packages (7)
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 |
|
BVP.Common.NET
Most important reusable code for BVP |
|
apex.net-Entities
Models for apex.net |
|
FileStorage.Accessor.Contracts
Package Description |
GitHub repositories (5)
Showing the top 5 popular GitHub repositories that depend on NetEscapades.EnumGenerators:
Repository | Stars |
---|---|
DSharpPlus/DSharpPlus
A .NET library for making bots using the Discord API.
|
|
Nexus-Mods/NexusMods.App
Home of the development of the Nexus Mods App
|
|
andrewlock/NetEscapades.EnumGenerators
A source generator for generating fast "reflection" methods for enums
|
|
xin9le/FastEnum
The world fastest enum utilities for C#/.NET
|
|
SteveDunn/Intellenum
Intelligent Enums
|
Version | Downloads | Last updated |
---|---|---|
1.0.0-beta12 | 81 | 1/26/2025 |
1.0.0-beta11 | 27,868 | 10/24/2024 |
1.0.0-beta09 | 110,104 | 5/15/2024 |
1.0.0-beta08 | 174,127 | 6/5/2023 |
1.0.0-beta07 | 82,301 | 3/10/2023 |
1.0.0-beta06 | 29,967 | 12/20/2022 |
1.0.0-beta05 | 266 | 12/19/2022 |
1.0.0-beta04 | 150,137 | 11/30/2021 |
1.0.0-beta03 | 1,910 | 11/26/2021 |
1.0.0-beta02 | 192 | 11/22/2021 |
1.0.0-beta01 | 397 | 11/18/2021 |
Breaking Changes:
- By default, `ToStringFast()` no longer uses `[DisplayName]` and `[Description]` by default. The original behaviour can be restored by passing `allowMatchingMetadataAttribute:true` (#122)
- Split the experimental interceptor support into a separate project, NetEscapades.EnumGenerators.Interceptors (#125)
- Enable interception by default when NetEscapades.EnumGenerators.Interceptors is added (#127)
Features
- Added a package logo (#125)
Fixes
- Fixed indentation in generated code so it aligns properly with 4 spaces (#120) Thanks @karl-sjogren!
- Fix missing global on System namespace usages (#118) Thanks @henrikwidlund!
- Don't use `using`s in generated code (#129)
See https://github.com/andrewlock/NetEscapades.EnumGenerators/blob/main/CHANGELOG.md#v100-beta12 for more details.