Advertisement
Guest User

EnumValues

a guest
Mar 13th, 2018
394
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.95 KB | None | 0 0
  1.     // Author contact: piecesof8bitgame@gmail.com
  2.  
  3.     /// <summary>
  4.     /// Helper to create and cache an array of all values of the specified enum type
  5.     /// Avoids constant garbage allocation from evaluating Enum.GetValues every time we want all values
  6.     /// </summary>
  7.     /// <typeparam name="TEnum">Type of an enum to use</typeparam>
  8.     public static class EnumValues<TEnum>
  9.         where TEnum : struct, IComparable, IConvertible, IFormattable
  10.     {
  11.         private static TEnum[] GetValues()
  12.         {
  13.             var values = Enum.GetValues(typeof(TEnum));
  14.  
  15.             var array = new TEnum[values.Length];
  16.             for (var i = 0; i < values.Length; i++)
  17.             {
  18.                 array[i] = (TEnum) values.GetValue(i);
  19.             }
  20.             return array;
  21.         }
  22.  
  23.         // NB: .NET 4.6 only; use a property with a private readonly backing field for .NET 3.5
  24.         public static TEnum[] Values { get; } = GetValues();
  25.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement