using System; using System.Collections.Generic; namespace DynamicEnums { /// /// A helper class that allows easier usage of regular values, as well as values. /// public static class EnumHelper { /// /// Returns an array containing all of the values of the given enum type. /// Note that this method is a version-independent equivalent of .NET 5's Enum.GetValues<TEnum>. /// /// The type whose enum to get /// An enumerable of the values of the enum, in declaration order. public static T[] GetValues() where T : struct, Enum { #if NET6_0_OR_GREATER return Enum.GetValues(); #else return (T[]) Enum.GetValues(typeof(T)); #endif } /// /// Returns true if the given has all of the given flags on it. /// This operation is equivalent to , but doesn't do any additional checks, making it faster. /// /// /// The value to query flags on. /// The flags to query. /// True if all of the flags are present, false otherwise. public static bool HasAllFlags(this T value, T flags) where T : struct, Enum { return (Convert.ToInt64(value) & Convert.ToInt64(flags)) == Convert.ToInt64(flags); } /// /// Returns true if the given has any of the given flags on it. /// /// /// The value to query flags on. /// The flags to query. /// True if any of the flags are present, false otherwise. public static bool HasAnyFlags(this T value, T flags) where T : struct, Enum { return (Convert.ToInt64(value) & Convert.ToInt64(flags)) != 0; } /// /// Returns all of the defined values from the given enum type which are contained in . /// Note that, if combined flags are defined in , and contains them, they will also be returned. /// /// The combined flags whose individual flags to return. /// Whether the enum value 0 should also be returned, if contains one. /// The type of enum. /// All of the flags that make up . public static IEnumerable GetFlags(T combinedFlag, bool includeZero = true) where T : struct, Enum { foreach (var flag in EnumHelper.GetValues()) { if (combinedFlag.HasAllFlags(flag) && (includeZero || Convert.ToInt64(flag) != 0)) yield return flag; } } /// /// Returns all of the defined unique flags from the given enum type which are contained in . /// Any combined flags (flags that aren't powers of two) which are defined in will not be returned. /// /// The combined flags whose individual flags to return. /// The type of enum. /// All of the unique flags that make up . public static IEnumerable GetUniqueFlags(T combinedFlag) where T : struct, Enum { var uniqueFlag = 1L; foreach (var flag in EnumHelper.GetValues()) { var flagValue = Convert.ToInt64(flag); // GetValues is always ordered by binary value, so we can be sure that the next flag is bigger than the last while (uniqueFlag < flagValue) uniqueFlag <<= 1; if (flagValue == uniqueFlag && combinedFlag.HasAllFlags(flag)) yield return flag; } } } }