-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
Background and motivation
The existing Type.GetEnumValues API returns a System.Array that is of the given enum type (i.e. SomeEnum[] when called on typeof(SomeEnum)). This makes implementing the API challenging when the enum array cannot be created. There are multiple reasons why the enum array might not be possible to create:
- We're in a reflection-only context such as
MetadataLoadContext:Line 289 in d6e8686
public sealed override Array GetEnumValues() => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection); - We're on a platform where runtime codegen (or universal shared code) is not available.
It would be good to have API that can work in these contexts by returning an array of the underlying type (i.e. int[] for typeof(SomeInt32Enum).
API Proposal
namespace System;
public abstract class Type
{
public virtual Array GetEnumValuesAsUnderlyingType();
}API Usage
foreach (var value in typeof(SomeEnum).GetEnumValuesAsUnderlyingType())
Console.WriteLine(value);
// Prints:
// 0
// 1
//
// As opposed to:
//
// SomeEnumValue1
// SomeEnumValue2Alternative Designs
Allow implementers to not satisfy the contract
The implementation of the existing Type.GetEnumValues could just return the underlying array directly since the signature is just System.Array. But that is probably pretty breaking - see #72236 (comment) for samples.
Write more code
Can be expressed in a less performant and more verbose way already:
foreach (var f in typeof(DayOfWeek).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
{
Console.WriteLine(f.Name);
Console.WriteLine(f.GetRawConstantValue()); // This returns the field value as boxed underlying type
}
Risks
No response