Repository navigation
Description
Enums are essential commonly used types but have several areas in need of improvement. For each non-generic Enum method there should be an equivalent generic version.
Rationale and Usage
- Nearly all of
Enum's static methods are non-generic leading to the following issues.- Requires boxing for methods with enum input parameters losing type-safety, eg.
IsDefinedandGetName. - Requires casting/unboxing for methods with an enum return value, eg.
ToObjectandGetValues. - Requires the enum type to be explicitly specified as an argument.
- Requires invocation using static method syntax.
- Requires boxing for methods with enum input parameters losing type-safety, eg.
With this proposal implemented what used to be this to validate a standard enum value
MyEnum value = ???;
bool isValid = Enum.IsDefined(typeof(MyEnum), value);now becomes this
MyEnum value = ???;
bool isValid = value.IsDefined();With this implemented it will address #18063.
Proposed API
namespace System {
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable {
public static TEnum Parse<TEnum>(ReadOnlySpan<char> value) where TEnum : struct, Enum;
public static TEnum Parse<TEnum>(ReadOnlySpan<char> value, bool ignoreCase) where TEnum : struct, Enum;
public static object Parse(Type enumType, ReadOnlySpan<char> value);
public static object Parse(Type enumType, ReadOnlySpan<char> value, bool ignoreCase);
public static bool TryParse<TEnum>(ReadOnlySpan<char> value, out TEnum result) where TEnum : struct, Enum;
public static bool TryParse<TEnum>(ReadOnlySpan<char> value, bool ignoreCase, out TEnum result) where TEnum : struct, Enum;
public static bool TryParse(Type enumType, ReadOnlySpan<char> value, out object result);
public static bool TryParse(Type enumType, ReadOnlySpan<char> value, bool ignoreCase, out object result);
// Generic versions of existing methods
public static string GetName<TEnum>(this TEnum value) where TEnum : struct, Enum;
public static IReadOnlyList<string> GetNames<TEnum>() where TEnum : struct, Enum;
public static IReadOnlyList<TEnum> GetValues<TEnum>() where TEnum : struct, Enum;
public static bool IsDefined<TEnum>(this TEnum value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(object value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(sbyte value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(byte value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(short value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(ushort value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(int value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(uint value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(long value) where TEnum : struct, Enum;
public static TEnum ToObject<TEnum>(ulong value) where TEnum : struct, Enum;
public static int CompareTo<TEnum>(TEnum value, TEnum other) where TEnum : struct, Enum;
public static bool Equals<TEnum>(TEnum value, TEnum other) where TEnum : struct, Enum;
public static byte ToByte<TEnum>(TEnum value) where TEnum : struct, Enum;
public static short ToInt16<TEnum>(TEnum value) where TEnum : struct, Enum;
public static int ToInt32<TEnum>(TEnum value) where TEnum : struct, Enum;
public static long ToInt64<TEnum>(TEnum value) where TEnum : struct, Enum;
public static sbyte ToSByte<TEnum>(TEnum value) where TEnum : struct, Enum;
public static string ToString<TEnum>(TEnum value) where TEnum : struct, Enum;
public static string ToString<TEnum>(TEnum value, string format) where TEnum : struct, Enum;
public static ushort ToUInt16<TEnum>(TEnum value) where TEnum : struct, Enum;
public static uint ToUInt32<TEnum>(TEnum value) where TEnum : struct, Enum;
public static ulong ToUInt64<TEnum>(TEnum value) where TEnum : struct, Enum;
}
}API Details
This proposal makes use of a C# language feature that needs to be added in order for this proposal to make the most impact.
This proposal specifies extension methods within System.Enum and as such requires C# to allow extension methods within non-static classes as is proposed in csharplang#301. Promoting these to extension methods later would be a breaking change due to csharplang#665 but I feel this is acceptable.
Alternatively, the extension methods could be defined in a separate static EnumExtensions class. This is uglier but would avoid this issue and the extension methods would be available immediately instead of needing to wait for a later C# version to support this.
Open Questions
- Is promoting the
System.Enumextension methods later an acceptable breaking change due to csharplang#665? If not should we wait for a laterC#version that supports extension methods inSystem.Enumor should we introduce a separateEnumExtensionsclass?
Implementation Details
This proposal stems from my work on the open source library Enums.NET which addresses each of these issues and will be the basis for an implementation. For efficiency this is how Enums.NET is implemented.
First, using Enum as a generic type argument causes generic code-explosion in today's runtimes so it's essential that it's included sparingly. For this reason most logic is contained in an EnumCache<TInt, TIntProvider> object where TInt is the underlying type and TIntProvider is the underlying type's operations provider which implements the interface INumericProvider<TInt> which provides the bitwise operations and other needed operations. Including the TIntProvider as a type parameter allows the runtime to inline calls to its methods so there's no interface method dispatch, a technique described in this generic calculations article.
Now how can one access this EnumCache object when the caller only has the enum type as a generic type argument? This is solved by the bridge-like object EnumInfo<TEnum, TInt, TIntProvider> which implements the interfaces IEnumInfo<TEnum> for generic methods and IEnumInfo for non-generic methods. It simply acts as a bridge to delegate calls from the interfaces to EnumCache<TInt, TIntProvider>. In order to do that it needs to be able to efficiently convert values between TEnum and TInt. This is performed by the conversion methods ToInt and ToEnum which are declared as extern methods for efficiency so that they're simply defined as casts from one type to the other. These method's functionality can be achieved with the Unsafe.As method. This EnumInfo<TEnum, TInt, TIntProvider> is created via reflection upon it's first call and is stored in the static field Enums<TEnum>.Info as an IEnumInfo<TEnum> which is then called by Enums's generic methods.
For non-generic methods the RuntimeType.GenericCache property will be set to the IEnumInfo to use.
Updates
- Added more implementation details.
- Added more API details.
- Added enumerating members usage example.
- Added generic versions of instance methods for performance reasons.
- Removed the
System.Enumsnamespace and moved its members into theSystemnamespace. - Moved
PrimaryAttributeinto theSystem.ComponentModelnamespace and switched to using the existingSystem.ComponentModel.AttributeCollection. - Removed
IsValidmethod as it's meaning is rather subjective and promotedIsValidFlagCombinationas an extension method. - Renamed
GetAllFlagstoAllFlagsas it more closely resembles a property but can't be because it is generic. Similar naming toArray.Empty. - Removed
EnumCompareras one can just useComparer<T>.DefaultandEqualityComparer<T>.Defaultinstead. - Split the proposed API to a base API addition and an
EnumMembersupport API addition. - Added
ReadOnlySpan<char>parse overloads. - Moved
FlagEnum.IsFlagEnumintoSystem.Enum. - No longer proposes adding the
Enumconstraint to existing methods. - Split
EnumMemberAPI addition into the separate issue dotnet/corefx#34077. - Split generic API additions that don't necessitate the performance improvements of this implementation to separate issue API Proposal: Add a Generic version of GetValues to Enum (probably GetName/GetNames) #2364.
- Split Flag API additions to separate issue dotnet/corefx#34079.
- Split
PrimaryAttributeaddition to separate issue dotnet/corefx#34080. - Moved
Formatto API Proposal: Add a Generic version of GetValues to Enum (probably GetName/GetNames) #2364 as well. - Moved proposed methods from API Proposal: Add a Generic version of GetValues to Enum (probably GetName/GetNames) #2364 back to this issue.
- Removed
Formatas it's no different fromToString(string format)except it throws anArgumentNullExceptionfor anullformatparameter.
Activity
TylerBrinkley commentedon Jan 26, 2017
Updated the proposal to include some more implementation details.
TylerBrinkley commentedon Jan 28, 2017
@danmosemsft I've updated the proposal to include more details about the new API defined.
svick commentedon Jan 28, 2017
There already is a proposal for that too: dotnet/roslyn#16271.
TylerBrinkley commentedon Jan 28, 2017
@svick Thanks, I've updated the proposal accordingly.
TylerBrinkley commentedon Jan 30, 2017
I've updated the proposal to include generic versions of instance methods for performance reasons.
TylerBrinkley commentedon Jan 31, 2017
@danmosemsft are you the CoreFX owner of this proposal. If so, could you let me know what needs to be done to get this API reviewed?
danmoseley commentedon Jan 31, 2017
@joperezr @AlexGhiondea are the owners of this area so one of them will either give feedback on it or flip to "api-ready-for-review".
TylerBrinkley commentedon Jan 31, 2017
Thanks @danmosemsft.
TylerBrinkley commentedon Feb 1, 2017
I've updated the proposal by removing the
System.Enumsnamespace and moved its members into theSystemnamespace. Does anyone thinkReadOnlyAttributeCollectionandPrimaryAttributeshould be included in another namespace, maybeSystem.ComponentModel?TylerBrinkley commentedon Feb 1, 2017
I see that there is already an
AttributeCollectionin theSystem.ComponentModelnamespace which would suit my needs with some additions but it's included in theSystem.ComponentModel.TypeConverterassembly. Are binding redirects possible in .NET Core to enable moving thisAttributeCollectionclass intomscorlib?danmoseley commentedon Feb 1, 2017
If it's an interesting type that we could use as is (or modify without breaking existing users) then it's possible for us to move it down so this code could depend on i.
TylerBrinkley commentedon Feb 1, 2017
Excellent, I'll update my proposal accordingly.
TylerBrinkley commentedon Feb 1, 2017
@joperezr @AlexGhiondea I believe I'm done with my proposal updates. When you have some time could you please look over this proposal?
magol commentedon Feb 1, 2017
I like the proposal a lot.
One api that I'm missing is a method that remove not valid flags.
public static TEnum RemoveNotValidFlags(this TEnum value) where TEnum : struct, Enum;
See #18190
TylerBrinkley commentedon Feb 1, 2017
For that case I'd suggest doing this.
I know it's less convenient but it seems too much of a specialized case to warrant a new extension method.
47 remaining items
huoyaoyuan commentedon Nov 22, 2019
What's about implementing
IEquatable<T>andIComparable<T>on enums? It looks not so simple, because enums do have metadata, unlike arrays being pure runtime-magic.Or skip it for 1 year and jump to type classes, which is planned for C# 10 and I assume to come with .NET 6?
mikernet commentedon Nov 22, 2019
@TylerBrinkley I'm not sure which approach you've taken to implement this but I just posted this comment which details a way to implement these operations with full bitwise operator speed. I thought I would mention it here as it turns out this appears to be the main discussion area for these.
When the methods are written like my example, they get inlined directly to bitwise operations and the branches are eliminated by the JIT so it produces very efficient code.
LegoCylon commentedon Dec 2, 2019
I'm not sure if you're interested in additional related features but I'd love to see support added to be able to enumerate values or names in the order they are defined (likely with an optional parameter on the GetNames and GetValues methods) since the current methods only enumerate in ascending value.
koszeggy commentedon Jun 17, 2020
Ha! It's funny to see that almost everyone implemented their well-performing enum library when it used to be so slow in the .NET Framework era. So did I, of course. :)
I'm really happy to see the improvements made in .NET Core. I would've never created my alternative version if
System.Enumwas always that fast. In fact, I needed to do a massive refactoring in my libraries, just to justify its today's existence and make it faster again than the Core version. :) But to be frank, maybe its last really useful feature that it supportsReadOnlySpan<char>, which is still not implemented in the System version.Anyhow, if it helps anything, feel free to re-use any solutions from it. Maybe it hasn't as many features as Tyler's version and my approach was also much simpler in some aspects, but who knows... maybe you can find some useful parts in it.
xaviergxf commentedon Aug 4, 2021
How about this api? Humanizr could use this...
huoyaoyuan commentedon Aug 4, 2021
Returning a span is never an option because of lifetime issue. Any api with result in span would require caller to allocate the span.
tannergooding commentedon Sep 9, 2022
As with #14084 this isn't a direction we'd like to move forward on.
The idiomatic bit operations are guaranteed to be efficient where-as these named methods aren't and potentially push users towards a pit of failure.