Skip to content

Commit 8be55f8

Browse files
committed
Improve performance of Enum's generic IsDefined / GetName / GetNames
Eliminates the boxing in IsDefined/GetName/GetValues, and in GetNames avoids having to go through RuntimeType's GetEnumNames override.
1 parent 54d27b2 commit 8be55f8

File tree

1 file changed

+17
-2
lines changed
  • src/libraries/System.Private.CoreLib/src/System

1 file changed

+17
-2
lines changed

src/libraries/System.Private.CoreLib/src/System/Enum.cs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,11 +258,26 @@ internal static ulong ToUInt64(object value)
258258
return result;
259259
}
260260

261+
private static ulong ToUInt64<TEnum>(TEnum value) where TEnum : struct, Enum =>
262+
Type.GetTypeCode(typeof(TEnum)) switch
263+
{
264+
TypeCode.SByte => (ulong)Unsafe.As<TEnum, sbyte>(ref value),
265+
TypeCode.Byte => Unsafe.As<TEnum, byte>(ref value),
266+
TypeCode.Boolean => Convert.ToByte(Unsafe.As<TEnum, bool>(ref value)),
267+
TypeCode.Int16 => (ulong)Unsafe.As<TEnum, short>(ref value),
268+
TypeCode.UInt16 => Unsafe.As<TEnum, ushort>(ref value),
269+
TypeCode.Char => Unsafe.As<TEnum, char>(ref value),
270+
TypeCode.UInt32 => Unsafe.As<TEnum, uint>(ref value),
271+
TypeCode.Int32 => (ulong)Unsafe.As<TEnum, int>(ref value),
272+
TypeCode.UInt64 => Unsafe.As<TEnum, ulong>(ref value),
273+
TypeCode.Int64 => (ulong)Unsafe.As<TEnum, long>(ref value),
274+
_ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
275+
};
261276
#endregion
262277

263278
#region Public Static Methods
264279
public static string? GetName<TEnum>(TEnum value) where TEnum : struct, Enum
265-
=> GetName(typeof(TEnum), value);
280+
=> GetEnumName((RuntimeType)typeof(TEnum), ToUInt64(value));
266281

267282
public static string? GetName(Type enumType, object value)
268283
{
@@ -273,7 +288,7 @@ internal static ulong ToUInt64(object value)
273288
}
274289

275290
public static string[] GetNames<TEnum>() where TEnum : struct, Enum
276-
=> GetNames(typeof(TEnum));
291+
=> new ReadOnlySpan<string>(InternalGetNames((RuntimeType)typeof(TEnum))).ToArray();
277292

278293
public static string[] GetNames(Type enumType)
279294
{

0 commit comments

Comments
 (0)