Created
June 11, 2022 19:59
-
-
Save ogxd/78226dd52eadc72c56421da61a60502d to your computer and use it in GitHub Desktop.
This file contains hidden or 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; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Ogxd; | |
/// <summary> | |
/// Returns a string for a given enum value, without allocations | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="value"></param> | |
/// <returns></returns> | |
public static string ToStringCached<T>(this T value) where T : Enum => EnumLabelsCache<T>.GetLabel(value); | |
/// <summary> | |
/// Returns all string labels for a given enum, without allocations | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <returns></returns> | |
public static IEnumerable<string> GetEnumLabels<T>() where T : Enum => EnumLabelsCache<T>.Labels; | |
/// <summary> | |
/// Returns all values for a given enum, without allocations | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <returns></returns> | |
public static IEnumerable<T> GetEnumValues<T>() where T : Enum => EnumLabelsCache<T>.Values; | |
private static class EnumLabelsCache<T> where T : Enum | |
{ | |
private static Dictionary<T, string> _labels; | |
static EnumLabelsCache() | |
{ | |
IEnumerable<T> values = Enum.GetValues(typeof(T)).Cast<T>(); | |
_labels = values.ToDictionary(t => t, t => t.ToString()); | |
} | |
internal static string GetLabel(T value) => _labels[value]; | |
internal static IEnumerable<string> Labels => _labels.Values; | |
internal static IEnumerable<T> Values => _labels.Keys; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment