{"id":13457951,"url":"https://github.com/andrewlock/NetEscapades.EnumGenerators","last_synced_at":"2025-03-24T14:32:59.202Z","repository":{"id":37448326,"uuid":"429221032","full_name":"andrewlock/NetEscapades.EnumGenerators","owner":"andrewlock","description":"A source generator for generating fast \"reflection\" methods for enums","archived":false,"fork":false,"pushed_at":"2025-03-11T21:21:44.000Z","size":636,"stargazers_count":991,"open_issues_count":14,"forks_count":50,"subscribers_count":9,"default_branch":"main","last_synced_at":"2025-03-19T22:05:17.792Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andrewlock.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-11-17T22:33:21.000Z","updated_at":"2025-03-13T15:14:22.000Z","dependencies_parsed_at":"2024-06-19T01:39:04.121Z","dependency_job_id":"c815f36e-269e-4d89-bd0c-2bb63c165f03","html_url":"https://github.com/andrewlock/NetEscapades.EnumGenerators","commit_stats":{"total_commits":90,"total_committers":11,"mean_commits":8.181818181818182,"dds":"0.15555555555555556","last_synced_commit":"7af68b91354a2ef5d4e804d8522ed58280e2a967"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrewlock%2FNetEscapades.EnumGenerators","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrewlock%2FNetEscapades.EnumGenerators/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrewlock%2FNetEscapades.EnumGenerators/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrewlock%2FNetEscapades.EnumGenerators/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andrewlock","download_url":"https://codeload.github.com/andrewlock/NetEscapades.EnumGenerators/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245066675,"owners_count":20555427,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T09:00:40.518Z","updated_at":"2025-03-24T14:32:59.196Z","avatar_url":"https://github.com/andrewlock.png","language":"C#","funding_links":[],"categories":["C\\#","Content","Source Generators"],"sub_categories":["20. [NetEscapades.EnumGenerators](https://ignatandrei.github.io/RSCG_Examples/v2/docs/NetEscapades.EnumGenerators) , in the [Enum](https://ignatandrei.github.io/RSCG_Examples/v2/docs/rscg-examples#enum) category","Enums"],"readme":"# ![](https://raw.githubusercontent.com/andrewlock/NetEscapades.EnumGenerators/refs/heads/main/icon_32.png) NetEscapades.EnumGenerators\n\n![Build status](https://github.com/andrewlock/NetEscapades.EnumGenerators/actions/workflows/BuildAndPack.yml/badge.svg)\n[![NuGet](https://img.shields.io/nuget/v/NetEscapades.EnumGenerators.svg)](https://www.nuget.org/packages/NetEscapades.EnumGenerators/)\n\nA Source Generator package that generates extension methods for enums, to allow fast \"reflection\".\n\n\u003e This source generator requires the .NET 7 SDK. You can target earlier frameworks like .NET Core 3.1 etc, but the _SDK_ must be at least 7.0.100\n\n\n## Why use this package?\n\nMany 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.\n\n\nFor example, the following benchmark shows the advantage of calling `ToStringFast()` over `ToString()`:\n\n``` ini\nBenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1348 (20H2/October2020Update)\nIntel Core i7-7500U CPU 2.70GHz (Kaby Lake), 1 CPU, 4 logical and 2 physical cores\n  DefaultJob : .NET Framework 4.8 (4.8.4420.0), X64 RyuJIT\n.NET SDK=6.0.100\n  DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT\n```\n\n|       Method |     FX |       Mean |     Error |    StdDev | Ratio |  Gen 0 | Allocated |\n|------------- |--------|-----------:|----------:|----------:|------:|-------:|----------:|\n| ToString |`net48` | 578.276 ns | 3.3109 ns | 3.0970 ns | 1.000 | 0.0458 |      96 B |\n| ToStringFast |`net48` |   3.091 ns | 0.0567 ns | 0.0443 ns | 0.005 |      - |         - |\n| ToString |`net6.0`| 17.985 ns | 0.1230 ns | 0.1151 ns | 1.000 | 0.0115 |      24 B |\n| ToStringFast |`net6.0`|  0.121 ns | 0.0225 ns | 0.0199 ns | 0.007 |      - |         - |\n\nEnabling these additional extension methods is as simple as adding an attribute to your enum:\n\n```csharp\n[EnumExtensions] // 👈 Add this\npublic enum Color\n{\n    Red = 0,\n    Blue = 1,\n}\n```\n\n## Adding NetEscapades.EnumGenerators to your project\n\nAdd the package to your application using\n\n```bash\ndotnet add package NetEscapades.EnumGenerators\n```\n\n\nThis adds a `\u003cPackageReference\u003e` to your project. You can additionally mark the package as `PrivateAssets=\"all\"` and `ExcludeAssets=\"runtime\"`.\n\n\u003e Setting `PrivateAssets=\"all\"` means any projects referencing this one won't get a reference to the _NetEscapades.EnumGenerators_ package. Setting `ExcludeAssets=\"runtime\"` ensures the _NetEscapades.EnumGenerators.Attributes.dll_ file is not copied to your build output (it is not required at runtime).\n\n```xml\n\u003cProject Sdk=\"Microsoft.NET.Sdk\"\u003e\n\n  \u003cPropertyGroup\u003e\n    \u003cOutputType\u003eExe\u003c/OutputType\u003e\n    \u003cTargetFramework\u003enet8.0\u003c/TargetFramework\u003e\n  \u003c/PropertyGroup\u003e\n\n  \u003c!-- Add the package --\u003e\n  \u003cPackageReference Include=\"NetEscapades.EnumGenerators\" Version=\"1.0.0-beta11\" \n    PrivateAssets=\"all\" ExcludeAssets=\"runtime\" /\u003e\n  \u003c!-- --\u003e\n\n\u003c/Project\u003e\n```\n\nAdding the package will automatically add a marker attribute, `[EnumExtensions]`, to your project.\n\nTo use the generator, add the `[EnumExtensions]` attribute to an enum. For example:\n\n```csharp\n[EnumExtensions]\npublic enum MyEnum\n{\n    First,\n\n    [Display(Name = \"2nd\")]\n    Second,\n}\n```\n\nThis will generate a class called `MyEnumExtensions` (by default), which contains a number of helper methods. For example:\n\n```csharp\npublic static partial class MyEnumExtensions\n{\n    public const int Length = 2;\n\n    public static string ToStringFast(this MyEnum value, bool useMetadataAttributes)\n        =\u003e useMetadataAttributes ? value.ToStringFastWithMetadata() : value.ToStringFast();\n\n    public static string ToStringFast(this MyEnum value)\n        =\u003e value switch\n        {\n            MyEnum.First =\u003e nameof(MyEnum.First),\n            MyEnum.Second =\u003e nameof(MyEnum.Second),\n            _ =\u003e value.ToString(),\n        };\n\n    private static string ToStringFastWithMetadata(this MyEnum value)\n        =\u003e value switch\n        {\n            MyEnum.First =\u003e nameof(MyEnum.First),\n            MyEnum.Second =\u003e \"2nd\",\n            _ =\u003e value.ToString(),\n        };\n\n    public static bool IsDefined(MyEnum value)\n        =\u003e value switch\n        {\n            MyEnum.First =\u003e true,\n            MyEnum.Second =\u003e true,\n            _ =\u003e false,\n        };\n\n    public static bool IsDefined(string name) =\u003e IsDefined(name, allowMatchingMetadataAttribute: false);\n\n    public static bool IsDefined(string name, bool allowMatchingMetadataAttribute)\n    {\n        var isDefinedInDisplayAttribute = false;\n        if (allowMatchingMetadataAttribute)\n        {\n            isDefinedInDisplayAttribute = name switch\n            {\n                \"2nd\" =\u003e true,\n                _ =\u003e false,\n            };\n        }\n\n        if (isDefinedInDisplayAttribute)\n        {\n            return true;\n        }\n\n        \n        return name switch\n        {\n            nameof(MyEnum.First) =\u003e true,\n            nameof(MyEnum.Second) =\u003e true,\n            _ =\u003e false,\n        };\n    }\n\n    public static MyEnum Parse(string? name)\n        =\u003e TryParse(name, out var value, false, false) ? value : ThrowValueNotFound(name);\n\n    public static MyEnum Parse(string? name, bool ignoreCase)\n        =\u003e TryParse(name, out var value, ignoreCase, false) ? value : ThrowValueNotFound(name);\n\n    public static MyEnum Parse(string? name, bool ignoreCase, bool allowMatchingMetadataAttribute)\n        =\u003e TryParse(name, out var value, ignoreCase, allowMatchingMetadataAttribute) ? value : throw new ArgumentException($\"Requested value '{name}' was not found.\");\n\n    public static bool TryParse(string? name, out MyEnum value)\n        =\u003e TryParse(name, out value, false, false);\n\n    public static bool TryParse(string? name, out MyEnum value, bool ignoreCase) \n        =\u003e TryParse(name, out value, ignoreCase, false);\n\n    public static bool TryParse(string? name, out MyEnum value, bool ignoreCase, bool allowMatchingMetadataAttribute)\n        =\u003e ignoreCase\n            ? TryParseIgnoreCase(name, out value, allowMatchingMetadataAttribute)\n            : TryParseWithCase(name, out value, allowMatchingMetadataAttribute);\n\n    private static bool TryParseIgnoreCase(string? name, out MyEnum value, bool allowMatchingMetadataAttribute)\n    {\n        if (allowMatchingMetadataAttribute)\n        {\n            switch (name)\n            {\n                case string s when s.Equals(\"2nd\", System.StringComparison.OrdinalIgnoreCase):\n                    value = MyEnum.Second;\n                    return true;\n                default:\n                    break;\n            };\n        }\n\n        switch (name)\n        {\n            case string s when s.Equals(nameof(MyEnum.First), System.StringComparison.OrdinalIgnoreCase):\n                value = MyEnum.First;\n                return true;\n            case string s when s.Equals(nameof(MyEnum.Second), System.StringComparison.OrdinalIgnoreCase):\n                value = MyEnum.Second;\n                return true;\n            case string s when int.TryParse(name, out var val):\n                value = (MyEnum)val;\n                return true;\n            default:\n                value = default;\n                return false;\n        }\n    }\n\n    private static bool TryParseWithCase(string? name, out MyEnum value, bool allowMatchingMetadataAttribute)\n    {\n        if (allowMatchingMetadataAttribute)\n        {\n            switch (name)\n            {\n                case \"2nd\":\n                    value = MyEnum.Second;\n                    return true;\n                default:\n                    break;\n            };\n        }\n\n        switch (name)\n        {\n            case nameof(MyEnum.First):\n                value = MyEnum.First;\n                return true;\n            case nameof(MyEnum.Second):\n                value = MyEnum.Second;\n                return true;\n            case string s when int.TryParse(name, out var val):\n                value = (MyEnum)val;\n                return true;\n            default:\n                value = default;\n                return false;\n        }\n    }\n\n    public static MyEnum[] GetValues()\n    {\n        return new[]\n        {\n            MyEnum.First,\n            MyEnum.Second,\n        };\n    }\n\n    public static string[] GetNames()\n    {\n        return new[]\n        {\n            nameof(MyEnum.First),\n            nameof(MyEnum.Second),\n        };\n    }\n}\n```\n\nIf 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:\n\n```csharp\npublic static bool HasFlagFast(this MyEnum value, MyEnum flag)\n    =\u003e flag == 0 ? true : (value \u0026 flag) == flag;\n```\n\nNote 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.\n\nYou 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.\n\n## Enabling interception\n\nInterceptors 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.\n\n\u003e 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](https://learn.microsoft.com/en-us/dotnet/core/porting/versioning-sdk-msbuild-vs), so you will need at least that version or higher.\n\nTo enable interception for a project, update to the latest version of _NetEscapades.EnumGenerators_ and set the `EnableEnumGeneratorInterceptor` property in your _.csproj_ to `true`:\n\n```xml\n\u003cProject Sdk=\"Microsoft.NET.Sdk\"\u003e\n\n  \u003cPropertyGroup\u003e\n    \u003cOutputType\u003eExe\u003c/OutputType\u003e\n    \u003cTargetFramework\u003enet8.0\u003c/TargetFramework\u003e\n    \u003c!-- 👇 Add this property to enable the interceptor in the project --\u003e\n    \u003cEnableEnumGeneratorInterceptor\u003etrue\u003c/EnableEnumGeneratorInterceptor\u003e\n  \u003c/PropertyGroup\u003e\n\n  \u003cItemGroup\u003e\n    \u003cPackageReference Include=\"NetEscapades.EnumGenerators\" Version=\"1.0.0-beta11\" \n    PrivateAssets=\"all\" ExcludeAssets=\"runtime\" /\u003e\n  \u003c/ItemGroup\u003e\n\n\u003c/Project\u003e\n```\n\nThis enables interception for all enums defined in the project that use the `[EnumExtensions]` or `[EnumExtensions\u003cT\u003e]` attributes. If you wish to intercept calls made to enums with extensions defined in _other_ projects, you must add the `[Interceptable\u003cT\u003e]` attribute in the project where you want the interception to happen, e.g.\n\n```csharp\n[assembly:Interceptable\u003cDateTimeKind\u003e]\n[assembly:Interceptable\u003cColor\u003e]\n```\n\nIf you don't want a specific enum to be intercepted, you can set the `IsInterceptable` property to `false`, e.g.\n\n```csharp\n[EnumExtensions(IsInterceptable = false)]\npublic enum Colour\n{\n    Red = 0,\n    Blue = 1,\n}\n```\n\nInterception only works when the target type is unambiguously an interceptable enum, so it won't work\n\n\n- When `ToString()` is called in other source generated code.\n- When `ToString()` is called in already-compiled code.\n- If the `ToString()` call is _implicit_ (for example in `string` interpolation)\n- If the `ToString()` call is made on a base type, such as `System.Enum` or `object`\n- If the `ToString()` call is made on a generic type\n\n## Embedding the attributes in your project\n\nBy 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:\n\n1. Define the MSBuild constant `NETESCAPADES_ENUMGENERATORS_EMBED_ATTRIBUTES`. This ensures the attributes are embedded in your project\n2. Add `compile` to the list of excluded assets in your `\u003cPackageReference\u003e` element. This ensures the attributes in your project are referenced, instead of the _NetEscapades.EnumGenerators.Attributes.dll_ library.\n\nYour project file should look something like this:\n\n```xml\n\u003cProject Sdk=\"Microsoft.NET.Sdk\"\u003e\n\n  \u003cPropertyGroup\u003e\n    \u003cOutputType\u003eExe\u003c/OutputType\u003e\n    \u003cTargetFramework\u003enet7.0\u003c/TargetFramework\u003e\n    \u003c!--  Define the MSBuild constant    --\u003e\n    \u003cDefineConstants\u003e$(DefineConstants);NETESCAPADES_ENUMGENERATORS_EMBED_ATTRIBUTES\u003c/DefineConstants\u003e\n  \u003c/PropertyGroup\u003e\n\n  \u003c!-- Add the package --\u003e\n  \u003cPackageReference Include=\"NetEscapades.EnumGenerators\" Version=\"1.0.0-beta11\" \n                    PrivateAssets=\"all\"\n                    ExcludeAssets=\"compile;runtime\" /\u003e\n\u003c!--                               ☝ Add compile to the list of excluded assets. --\u003e\n\n\u003c/Project\u003e\n```\n\n## Preserving usages of the `[EnumExtensions]` attribute\n\nThe `[EnumExtensions]` attribute is decorated with the `[Conditional]` attribute, [so their usage will not appear in the build output of your project](https://andrewlock.net/conditional-compilation-for-ignoring-method-calls-with-the-conditionalattribute/#applying-the-conditional-attribute-to-classes). If you use reflection at runtime on one of your `enum`s, you will not find `[EnumExtensions]` in the list of custom attributes.\n\nIf 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.\n\n```xml\n\u003cProject Sdk=\"Microsoft.NET.Sdk\"\u003e\n\n  \u003cPropertyGroup\u003e\n    \u003cOutputType\u003eExe\u003c/OutputType\u003e\n    \u003cTargetFramework\u003enet8.0\u003c/TargetFramework\u003e\n    \u003c!--  Define the MSBuild constant to preserve usages   --\u003e\n    \u003cDefineConstants\u003e$(DefineConstants);NETESCAPADES_ENUMGENERATORS_USAGES\u003c/DefineConstants\u003e\n  \u003c/PropertyGroup\u003e\n\n  \u003c!-- Add the package --\u003e\n  \u003cPackageReference Include=\"NetEscapades.EnumGenerators\" Version=\"1.0.0-beta11\" PrivateAssets=\"all\" /\u003e\n  \u003c!--              ☝ You must not exclude the runtime assets in this case --\u003e\n\n\u003c/Project\u003e\n```\n\n## Error CS0436 and [InternalsVisibleTo]\n\n\u003e In the latest version of _NetEscapades.EnumGenerators_, you should not experience error CS0436 by default.\n\nIn 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:\n\n```bash\nwarning 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'.\n```\n\nIn 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.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrewlock%2FNetEscapades.EnumGenerators","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandrewlock%2FNetEscapades.EnumGenerators","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrewlock%2FNetEscapades.EnumGenerators/lists"}