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 https://github.com/dotnet/coreclr/pull/6687
/cc @terrajobst
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+.
This is something we should consider.
The next step would be to have a formal API proposal written and have it reviewed.
I've created a formal API proposal dotnet/corefx#15453 that addresses this request.
Most helpful comment
I've created a formal API proposal dotnet/corefx#15453 that addresses this request.