• Stars
    star
    944
  • Rank 48,415 (Top 1.0 %)
  • Language
    C#
  • License
    MIT License
  • Created about 3 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A source generator for generating fast "reflection" methods for enums

NetEscapades.EnumGenerators

Build status NuGet

A Source Generator package that generates extension methods for enums, to allow fast "reflection".

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

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. Setting ExcludeAssets="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>net6.0</TargetFramework>
  </PropertyGroup>

  <!-- Add the package -->
  <PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta04" 
    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)
        => 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)
        => name switch
        {
            nameof(MyEnum.First) => true,
            nameof(MyEnum.Second) => true,
            _ => false,
        };

    public static bool TryParse(
        [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] string? name, 
        bool ignoreCase, 
        out MyEnum value)
        => ignoreCase ? TryParseIgnoreCase(name, out value) : TryParse(name, out value);

    private static bool TryParseIgnoreCase(
        [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] string? name, 
        out MyEnum value)
    {
        switch (name)
        {
            case { } s when s.Equals(nameof(MyEnum.First), System.StringComparison.OrdinalIgnoreCase):
                value = MyEnum.First;
                return true;
            case { } s when s.Equals(nameof(MyEnum.Second), System.StringComparison.OrdinalIgnoreCase):
                value = MyEnum.Second;
                return true;
            case { } s when int.TryParse(name, out var val):
                value = (MyEnum)val;
                return true;
            default:
                value = default;
                return false;
        }
    }

    public static bool TryParse(
        [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] string? name, 
        out MyEnum value)
    {
        switch (name)
        {
            case nameof(MyEnum.First):
                value = MyEnum.First;
                return true;
            case nameof(MyEnum.Second):
                value = MyEnum.Second;
                return true;
            case { } 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.

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:

  1. Define the MSBuild constant NETESCAPADES_ENUMGENERATORS_EMBED_ATTRIBUTES. This ensures the attributes are embedded in your project
  2. 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>net6.0</TargetFramework>
    <!--  Define the MSBuild constant    -->
    <DefineConstants>$(DefineConstants);NETESCAPADES_ENUMGENERATORS_EMBED_ATTRIBUTES</DefineConstants>
  </PropertyGroup>

  <!-- Add the package -->
  <PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta04" 
                    PrivateAssets="all"
                    ExcludeAssets="compile;runtime" />
<!--                               ☝ Add compile to the list of excluded assets. -->

</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 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. 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>net6.0</TargetFramework>
    <!--  Define the MSBuild constant to preserve usages   -->
    <DefineConstants>$(DefineConstants);NETESCAPADES_ENUMGENERATORS_USAGES</DefineConstants>
  </PropertyGroup>

  <!-- Add the package -->
  <PackageReference Include="NetEscapades.EnumGenerators" Version="1.0.0-beta05" PrivateAssets="all" />
  <!--              ☝ You must not exclude the runtime assets in this case -->

</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 StronglyTypedId, 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.

More Repositories

1

StronglyTypedId

A Rosyln-powered generator for strongly-typed IDs
C#
1,504
star
2

NetEscapades.AspNetCore.SecurityHeaders

Small package to allow adding security headers to ASP.NET Core websites
C#
634
star
3

blog-examples

Sample applications for blog posts on https://andrewlock.net
HTML
389
star
4

NetEscapades.Configuration

Additional configuration providers to use with ASP.NET Core
C#
293
star
5

asp-dot-net-core-in-action-2e

Source code examples for ASP.NET Core in Action, Second Edition
C#
276
star
6

asp-dot-net-core-in-action

Source code examples for ASP.NET Core in Action
C#
205
star
7

asp-dot-net-core-in-action-3e

Source code examples for ASP.NET Core in Action, Third Edition
C#
146
star
8

PwnedPasswords

An ASP.NET Core Identity validator that checks for PwnedPasswords
C#
103
star
9

NetEscapades.Extensions.Logging

A rolling file logging provider for ASP.NET Core 2.0
C#
96
star
10

CommonPasswordsValidator

Implementations of ASP.NET Core Identity IPasswordValidators that verify the provided password is not one of the most common passwords.
C#
57
star
11

dotnet-config2json

A simple tool to convert a web.config file to an appsettings.json file
C#
37
star
12

NetEscapades.AspNetCore.StartupTasks

Small library for running tasks asynchronously on ASP.NET Core app startup
C#
20
star
13

dotnet-tinify

A simple tool for squashing PNG and JPEG files using the TinyPNG API
C#
20
star
14

NetEscapades.AspNetCore.Identity.Validators

A collection of ASP.NET Core Identity IPasswordValidators
C#
19
star
15

aspnetcore-in-docker

Basic web app demonstrating how to containerise an ASP.NET Core app.
C#
19
star
16

NetEscapades.AspNetCore.TagHelpers

A collection of Tag Helpers for ASP.NET Core projects
C#
14
star
17

AsciiMath

An AsciiMath parser and converter for .NET
C#
12
star
18

NetEscapades.Templates

Templates for use with the the .NET CLI's dotnet new functionality
C#
12
star
19

docker-dotnet-mono

A docker image that contains the .NET Core 2.1 SDK and Mono
Dockerfile
12
star
20

convert-disqus-to-giscus

A small .NET script/tool for converting Disqus comments to giscus
C#
11
star
21

TwilioSamples

C#
9
star
22

auto-assign-issues

An app to auto-assign any issues raised in a repository to specific users
TypeScript
4
star
23

nerdbank-gitversioning

A docker image with the Nerdbank.GitVersioning .NET Core CLI tool installed
Dockerfile
3
star
24

source-generator-test

C#
3
star
25

BlogFunctions

Azure functions for deploying https://andrewlock.net
C#
2
star
26

GitHubAffectedFiles

A small self-contained executable for printing the list of files between two commits
C#
2
star
27

aspnetcore-builder

A generalised Dockerfile for building ASP.NET Core apps
Dockerfile
1
star
28

blog-disqus

HTML
1
star
29

dotnet-docker-images

A builder for various docker images with .NET installed
Dockerfile
1
star
30

NetEscapades.GitVersioning.GitHub

C#
1
star
31

aspnetcore-cake-builder

A generalised Docker image for building apps using Cake
C#
1
star
32

blog-comments

The blog comments discussions for https://andrewlock.net
1
star