Created
October 20, 2023 22:39
-
-
Save Blokyk/2954b14d4583a1a6f9b44c3e6dcd0f62 to your computer and use it in GitHub Desktop.
Access info about a generic TEnum type in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.CompilerServices; | |
/// <summary> | |
/// Computes various properties of <typeparamref name="TEnum"/> | |
/// </summary> | |
/// <remarks>WARNING: This assumes that <typeparamref name="TEnum"/>'s underlying type is an <see langword="int"/></remarks> | |
public static class EnumInfo<TEnum> where TEnum : struct, Enum | |
{ | |
private static readonly Lazy<HashSet<TEnum>> _valuesSet = new(static () => new HashSet<TEnum>(EnumValues!)); | |
static EnumInfo() { | |
EnumValues = Enum.GetValues<TEnum>(); | |
EnumValuesAsInt = new int[EnumValues.Length]; | |
IsEmpty = EnumValues.Length == 0; | |
int min = Int32.MaxValue, max = Int32.MinValue; | |
for (int i = 0; i < EnumValues.Length; i++) { | |
var val = EnumValues[i]; | |
var valAsInt = EnumValuesAsInt[i] = Unsafe.As<TEnum, int>(ref val); | |
if (valAsInt < min) | |
min = valAsInt; | |
else if (valAsInt > max) | |
max = valAsInt; | |
} | |
} | |
// static initialization can be funky so i prefer init'ing those in the cctor | |
public static bool IsEmpty { get; } | |
public static int MinValue { get; } | |
public static int MaxValue { get; } | |
public static TEnum[] EnumValues { get; } | |
public static int[] EnumValuesAsInt { get; } | |
public static bool IsValid(TEnum value) => _valuesSet.Value.Contains(value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment