Skip to content

[Proposal] Add Enum.IsDefined() method #18063

Closed

Description

@benaadams

So rather than doing this:

string DoTheThing(MyEnum argument)
{
    if (!Enum.IsDefined(typeof(MyEnum), argument))
    {
         Log.Warn(...);
         return String.Empty;
    }
    return argument.ToString();
}

You can do this:

string DoTheThing(MyEnum argument)
{
    if (!argument.IsDefined())
    {
         Log.Warn(...);
         return String.Empty;
    }
    return argument.ToString();
}

Enum.IsDefined(typeof(MyEnum), argument) is also quite slow as it needs to do lots of conversion checks etc; whereas if you already have the enum these don't need to be done.

e.g.
https://github.com/dotnet/corefx/blob/master/src/System.Private.Uri/src/System/UriExt.cs#L19-L24

Suggested change dotnet/coreclr#6687

/cc @terrajobst

Activity

  1. changed the title [-]Add Enum.IsDefined() method[/-] [+][Proposal] Add Enum.IsDefined() method[/+] on Aug 10, 2016
  2. TylerBrinkley commented on Nov 5, 2016

    @TylerBrinkley
    Contributor

    I apologize for the shameless plug but I believe this is pertinent to users. I've just released version 1.0.0 of Enums.NET, a high-performance type-safe .NET enum utility library.

    It has the extension method IsDefined that is constrained to the enum type which addresses this issue.

    It also has the extension method IsValid that for flag enums checks if it's a valid combination of the defined flags or for standard enums checks if it's defined.

    Enums.NET is available on NuGet and is compatible with .NET Standard 1.0+ as well as .NET Framework 2.0+.

  3. AlexGhiondea commented on Nov 30, 2016

    @AlexGhiondea
    Contributor

    This is something we should consider.

    The next step would be to have a formal API proposal written and have it reviewed.

  4. TylerBrinkley commented on Jan 25, 2017

    @TylerBrinkley
    Contributor

    I've created a formal API proposal dotnet/corefx#15453 that addresses this request.

  5. transferred this issue fromdotnet/corefxon Jan 31, 2020
  6. added this to the 5.0 milestone on Jan 31, 2020
  7. added
    untriaged
    on Feb 23, 2020
  8. modified the milestones: 5.0.0, Future on Jul 6, 2020
  9. removed
    untriaged
    on Jul 6, 2020
  10. ghost locked as resolved and limited conversation to collaborators on Dec 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions