Skip to content

[API Proposal]: Type.GetEnumValuesAsUnderlyingType #72498

@MichalStrehovsky

Description

@MichalStrehovsky

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:

  1. We're in a reflection-only context such as MetadataLoadContext:
    public sealed override Array GetEnumValues() => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
  2. 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
// SomeEnumValue2

Alternative 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.ReflectionblockingMarks issues that we want to fast track in order to unblock other important work

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions