| | | 1 | | using System; |
| | | 2 | | using System.Linq; |
| | | 3 | | |
| | | 4 | | namespace AmbientServices.Utilities; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// A static class that holds extensions to the system <see cref="Enum"/> class. |
| | | 8 | | /// </summary> |
| | | 9 | | /// <remarks> |
| | | 10 | | /// <pitch>The largest defined value of an enum type without paying reflection cost on every call.</pitch> |
| | | 11 | | /// <plan>Delegates to <see cref="EnumMax{T}"/>, whose static initializer enumerates the enum's defined values once per |
| | | 12 | | /// </remarks> |
| | | 13 | | internal static class EnumUtilities |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Returns the highest possible value for an enum. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <typeparam name="T">The enum to get the maximum value for.</typeparam> |
| | | 19 | | /// <returns>The highest enum value.</returns> |
| | | 20 | | public static T MaxEnumValue<T>() where T : Enum |
| | | 21 | | { |
| | 2 | 22 | | return EnumMax<T>.Max; |
| | | 23 | | } |
| | | 24 | | } |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// A static class that holds onto the computed max enum value. |
| | | 28 | | /// </summary> |
| | | 29 | | /// <typeparam name="T"></typeparam> |
| | | 30 | | /// <remarks> |
| | | 31 | | /// <pitch>The per-enum-type cache backing <see cref="EnumUtilities.MaxEnumValue{T}"/>; the CLR's generic static initial |
| | | 32 | | /// </remarks> |
| | | 33 | | internal static class EnumMax<T> where T : Enum |
| | | 34 | | { |
| | | 35 | | private static T Init() |
| | | 36 | | { |
| | | 37 | | Array a = Enum.GetValues(typeof(T))!; // I don't think it's possible to have a System.Enum for which Enum.GetV |
| | | 38 | | return a.Length == 0 |
| | | 39 | | ? default! // apparently the compiler isn't smart enough to know that even though S |
| | | 40 | | : a.Cast<T>().Max()!; |
| | | 41 | | } |
| | | 42 | | public static T Max { get; } = Init(); |
| | | 43 | | } |