Skip to content

Devirtualise Enum.ToString() / prevent boxing #6482

@benaadams

Description

@benaadams
enum MyEnum { One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten };
// ...
(MyEnum.Seven).ToString();

Will box on the .ToString()

Could the following method be added to Enum

protected unsafe static string ToString<TEnum>(TEnum e, int size) where TEnum : struct
{
    ulong ul = 0;
    switch (size)
    {
        case 1:
        case 2:
        case 4:
            var i = JitHelpers.UnsafeEnumCast(e);
            if (Enum.GetUnderlyingType(typeof(TEnum)) == typeof(uint)
                || Enum.GetUnderlyingType(typeof(TEnum)) == typeof(ushort)
                || Enum.GetUnderlyingType(typeof(TEnum)) == typeof(byte))
                ul = (ulong)(uint)i;
            else
                ul = (ulong)i;
            break;
        case 8:
            ul = (ulong)JitHelpers.UnsafeEnumCastLong(e);
            break;
    }
    return Enum.InternalFormat((RuntimeType)typeof(TEnum), ul) ?? e.ToString();
}

Then when the enum types are compiled they can have a .ToString method as follows

public override string ToString() => Enum.ToString(this, sizeof(MyEnum));

Just an idea... (or jit something better)

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationapi-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtimetenet-performancePerformance related issue

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions