You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
API Proposal: Add a Generic version of GetValues to Enum (probably GetName/GetNames) #2364
I suggest to implement Generic version of GetValues method in the Enum class.
In present, if we going to get an typed array of some enum values we have to write following code: SomeEnum[] values = (SomeEnum[])Enum.GetValues(typeof(SomeEnum));
It seems as unconvenient way.
In my opinion, the following Generics-based syntax should seems shorter, more convenient and safely (by reason of type casting necessity): SomeEnum[] values = Enum.GetValues<SomeEnum>();
The possible way to implement this syntax is:
public static TEnum[] GetValues<TEnum>() where TEnum : struct
{
Type enumType = typeof(TEnum);
return (TEnum[])enumType.GetEnumValues();
}
This proposal is inspired by the great Generic-based version of Enum.TryParse method laying besides with legacy non-Generic version:
public static bool TryParse(Type enumType, String value, out Object result)
public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct
If proposal to implement Generic version of GetValues will be accepted I guess following Generics-based implementations of GetName GetNames should be implemented for symmetry reason:
public static String GetName<TEnum>(Object value) where TEnum : struct
{
Type enumType = typeof(TEnum);
return enumType.GetEnumName(value);
}
public static String[] GetNames<TEnum>() where TEnum : struct
{
Type enumType = typeof(TEnum);
return enumType.GetEnumNames();
}
This is a small point improvement suggestion.
It can be implemented separately of as a part of total Enum improvements discussing in dotnet/corefx/#15453
Reacted by BhaaL, David Pine, Matthew White, Max, Eugene Peshkov, Joseph Musser, Marco Rossignoli, Tyler Brinkley, Misa Jovanovic, Steve B and 12 more
changed the title [-]Add a Generic version of GetValues to Enum (probably GetName/GetNames)[/-][+]API Proposal: Add a Generic version of GetValues to Enum (probably GetName/GetNames)[/+]on Feb 26, 2018
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. IsDefined and GetName.
Requires casting/unboxing for methods with an enum return value, eg. ToObject and GetValues.
Requires the enum type to be explicitly specified as an argument.
Requires invocation using static method syntax.
With this proposal implemented what used to be this to validate a standard enum value
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.Enum extension methods later an acceptable breaking change due to csharplang#665? If not should we wait for a later C# version that supports extension methods in System.Enum or should we introduce a separate EnumExtensions class?
Updates
Changed GetNames and GetValues to return an IReadOnlyList instead of IEnumerable.
This looks reasonable and we agree that it makes calling code nicer. @tannergooding brought up runtime concerns around polluting generic instantiations. @jkotas what are your thoughts on this?
Right, just want to confirm that there isn't any concern around adding a generic API to a non-generic type. IIRC, there was concerns raised around that in the past.
I've moved those proposed API's back to dotnet/corefx#15453.
I'm especially opposed to returning an array for GetValues as an array cannot be reused and must be allocated on each call. It should instead return an IReadOnlyList<TEnum> as that could then be shared even if the current implementation doesn't do so.
We do have a number of non-generic methods in the surface. How are we deciding when it is worth creating duplicate generic wrapper to save a bit of typing, e.g. why not have generic versions of Enum.GetName, Enum.IsDefined or Attribute.GetCustomAttributes too?
If Enum.GetValues is different enough from the other APIs to deserve the generic wrapper, I do not have a problem with adding it.
returning an array for GetValues as an array cannot be reused
Does it really matter? Enum.GetValues is not the kind of API that is likely to be on a hot-path, and returning interface instead of array would add a different kind of overhead.
Does it really matter? Enum.GetValues is not the kind of API that is likely to be on a hot-path, and returning interface instead of array would add a different kind of overhead.
It's common to use enums to represent options in a dropdown and if GetValues returns an array then each time a page is requested with that dropdown it will add non-insignificant allocations, especially when there are many options.
It will be a single allocation (the array) that is relatively small overall (even for the full country list, you are looking at under 2kb for the array, if you assume ~200 countries and 8 bytes per entry).
@tannergooding How do you use an array pool here, when the implementation of GetValues creates the array, but only the caller knows when it's no longer necessary?
FWIW, from my benchmarking in dotnet/coreclr#22161 the current implementation of the non-generic version of this method allocates much more than would be expected, about 1kb for an enum with 36 members.
The lack of convenient enum reflection APIs has been long-standing. At a minimum, there should be a maximally convenient API for all common enum reflection scenarios.
If such a convenient API does not have good performance it might make sense to add a high-performance API in some form.
But callers can already ensure optimal performance by doing caching work themselves.
IMO, the most important use case, that is not currently served, is a convenient API.
I have seen many enum tickets on this issue tracker. I think it would be best if all of them were looked at together and a holistic solution was implemented.
Activity
[-]Add a Generic version of GetValues to Enum (probably GetName/GetNames)[/-][+]API Proposal: Add a Generic version of GetValues to Enum (probably GetName/GetNames)[/+]terrajobst commentedon Oct 10, 2018
While @joperezr owns this are I believe this issue is read for an API review. @joperezr, feel free to unmark if you think otherwise 😄
TylerBrinkley commentedon Dec 13, 2018
Split off from dotnet/corefx#15453
Enums are essential commonly used types but have several areas in need of improvement. For each non-generic
Enummethod there should be an equivalent generic version.Rationale and Usage
Enum's static methods are non-generic leading to the following issues.IsDefinedandGetName.ToObjectandGetValues.With this proposal implemented what used to be this to validate a standard enum value
now becomes this
With this implemented it will address dotnet/corefx#10692.
Proposed API
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.Enumand as such requiresC#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
EnumExtensionsclass. This is uglier but would avoid this issue and the extension methods would be available immediately instead of needing to wait for a laterC#version to support this.Open Questions
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?Updates
GetNamesandGetValuesto return anIReadOnlyListinstead ofIEnumerable.Format.terrajobst commentedon Aug 27, 2019
@TylerBrinkley
This looks like a separate proposal. Let's keep this focused on just this API:
This looks reasonable and we agree that it makes calling code nicer. @tannergooding brought up runtime concerns around polluting generic instantiations. @jkotas what are your thoughts on this?
tannergooding commentedon Aug 27, 2019
Right, just want to confirm that there isn't any concern around adding a generic API to a non-generic type. IIRC, there was concerns raised around that in the past.
TylerBrinkley commentedon Aug 27, 2019
I've moved those proposed API's back to dotnet/corefx#15453.
I'm especially opposed to returning an array for
GetValuesas an array cannot be reused and must be allocated on each call. It should instead return anIReadOnlyList<TEnum>as that could then be shared even if the current implementation doesn't do so.jkotas commentedon Aug 27, 2019
We do have a number of non-generic methods in the surface. How are we deciding when it is worth creating duplicate generic wrapper to save a bit of typing, e.g. why not have generic versions of
Enum.GetName,Enum.IsDefinedorAttribute.GetCustomAttributestoo?If
Enum.GetValuesis different enough from the other APIs to deserve the generic wrapper, I do not have a problem with adding it.Does it really matter?
Enum.GetValuesis not the kind of API that is likely to be on a hot-path, and returning interface instead of array would add a different kind of overhead.TylerBrinkley commentedon Aug 28, 2019
It's common to use enums to represent options in a dropdown and if
GetValuesreturns an array then each time a page is requested with that dropdown it will add non-insignificant allocations, especially when there are many options.tannergooding commentedon Aug 28, 2019
It will be a single allocation (the array) that is relatively small overall (even for the full country list, you are looking at under 2kb for the array, if you assume ~200 countries and 8 bytes per entry).
tannergooding commentedon Aug 28, 2019
The cost of the allocation could also be amortized by caching on the UX side or be utilizing an array pool.
TylerBrinkley commentedon Aug 28, 2019
That's true. If a server were to do the caching that would reduce the allocation cost.
I'd still prefer it to return an
IReadOnlyList<TEnum>but acknowledge returning an array would be acceptable.svick commentedon Aug 28, 2019
@tannergooding How do you use an array pool here, when the implementation of
GetValuescreates the array, but only the caller knows when it's no longer necessary?TylerBrinkley commentedon Aug 28, 2019
FWIW, from my benchmarking in dotnet/coreclr#22161 the current implementation of the non-generic version of this method allocates much more than would be expected, about 1kb for an enum with 36 members.
GSPP commentedon Sep 2, 2019
The lack of convenient enum reflection APIs has been long-standing. At a minimum, there should be a maximally convenient API for all common enum reflection scenarios.
If such a convenient API does not have good performance it might make sense to add a high-performance API in some form.
But callers can already ensure optimal performance by doing caching work themselves.
IMO, the most important use case, that is not currently served, is a convenient API.
I have seen many enum tickets on this issue tracker. I think it would be best if all of them were looked at together and a holistic solution was implemented.
terrajobst commentedon Sep 24, 2019
Video
I stand corrected, we believe we'd prefer this API shape:
11 remaining items
TylerBrinkley commentedon Oct 11, 2019
I'd love to submit the PR for these additions but would like to wait until the repo's are merged before doing so if no one else objects.
TylerBrinkley commentedon Oct 11, 2019
Also, with nullability now in C# 8,
GetNameshould returnstring?asnullis returned when the value is not defined.terrajobst commentedon Oct 11, 2019
No objections; this is going to be a 5.0 feature anyway.
danmoseley commentedon Jan 29, 2020
@TylerBrinkley still interested?
danmoseley commentedon Jan 29, 2020
re-adding approved label