<p>I need to validate an integer to know if is a valid enum value.</p>

<p>What is the best way to do this in C#?</p>

[{'answer_id': 13635, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 3, 'selected': False, 'text': '<p>Brad Abrams specifically warns against <strong><code>Enum.IsDefined</code></strong> in his post <a href="https://learn.microsoft.com/en-us/archive/blogs/brada/the-danger-of-over-simplification-enum-isdefined" rel="nofollow noreferrer">The Danger of Oversimplification</a>. </p>\n\n<p>The best way to get rid of this requirement (that is, the need to validate enums) is to remove ways where users can get it wrong, e.g., an input box of some sort. Use enums with drop downs, for example, to enforce only valid enums.</p>\n'}, {'answer_id': 13651, 'author': 'Mike Polen', 'author_id': 212, 'author_profile': 'https://Stackoverflow.com/users/212', 'pm_score': 0, 'selected': False, 'text': '<p>I found this <a href="http://www.cambiaresearch.com/c4/52a7e5fe-c7fc-49ab-b21d-37e6194687f3/Convert-Integer-To-Enum-Instance-in-csharp.aspx" rel="nofollow noreferrer">link</a> that answers it quite well. It uses:</p>\n\n<pre><code>(ENUMTYPE)Enum.ToObject(typeof(ENUMTYPE), INT)\n</code></pre>\n'}, {'answer_id': 4807469, 'author': 'Vman', 'author_id': 299529, 'author_profile': 'https://Stackoverflow.com/users/299529', 'pm_score': 8, 'selected': True, 'text': '<p>You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!</p>\n\n<p><code>IsDefined</code> is fine for most scenarios, you could start with:</p>\n\n<pre><code>public static bool TryParseEnum&lt;TEnum&gt;(this int enumValue, out TEnum retVal)\n{\n retVal = default(TEnum);\n bool success = Enum.IsDefined(typeof(TEnum), enumValue);\n if (success)\n {\n  retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);\n }\n return success;\n}\n</code></pre>\n\n<p>(Obviously just drop the ‘this’ if you don’t think it’s a suitable int extension)</p>\n'}, {'answer_id': 15752719, 'author': 'deegee', 'author_id': 1655625, 'author_profile': 'https://Stackoverflow.com/users/1655625', 'pm_score': 5, 'selected': False, 'text': '<p>IMHO the post marked as the answer is incorrect.<br>\nParameter and data validation is one of the things that was drilled into me decades ago.</p>\n\n<p><strong>WHY</strong></p>\n\n<p>Validation is required because essentially any integer value can be assigned to an enum without throwing an error.<br>\nI spent many days researching C# enum validation because it is a necessary function in many cases.</p>\n\n<p><strong>WHERE</strong></p>\n\n<p>The main purpose in enum validation for me is in validating data read from a file: you never know if the file has been corrupted, or was modified externally, or was hacked on purpose.<br>\nAnd with enum validation of application data pasted from the clipboard: you never know if the user has edited the clipboard contents.</p>\n\n<p>That said, I spent days researching and testing many methods including profiling the performance of every method I could find or design.</p>\n\n<p>Making calls into anything in System.Enum is so slow that it was a noticeable performance penalty on functions that contained hundreds or thousands of objects that had one or more enums in their properties that had to be validated for bounds.</p>\n\n<p>Bottom line, stay away from <em>everything</em> in the System.Enum class when validating enum values, it is dreadfully slow.</p>\n\n<p><strong>RESULT</strong></p>\n\n<p>The method that I currently use for enum validation will probably draw rolling eyes from many programmers here, but it is imho the least evil for my specific application design.</p>\n\n<p>I define one or two constants that are the upper and (optionally) lower bounds of the enum, and use them in a pair of if() statements for validation.<br>\nOne downside is that you must be sure to update the constants if you change the enum.<br>\nThis method also only works if the enum is an "auto" style where each enum element is an incremental integer value such as 0,1,2,3,4,....  It won\'t work properly with Flags or enums that have values that are not incremental.</p>\n\n<p>Also note that this method is almost as fast as regular if "&lt;" ">" on regular int32s (which scored 38,000 ticks on my tests).</p>\n\n<p>For example:</p>\n\n<pre><code>public const MyEnum MYENUM_MINIMUM = MyEnum.One;\npublic const MyEnum MYENUM_MAXIMUM = MyEnum.Four;\n\npublic enum MyEnum\n{\n    One,\n    Two,\n    Three,\n    Four\n};\n\npublic static MyEnum Validate(MyEnum value)\n{\n    if (value &lt; MYENUM_MINIMUM) { return MYENUM_MINIMUM; }\n    if (value &gt; MYENUM_MAXIMUM) { return MYENUM_MAXIMUM; }\n    return value;\n}\n</code></pre>\n\n<p><strong>PERFORMANCE</strong></p>\n\n<p>For those who are interested, I profiled the following variations on an enum validation, and here are the results.</p>\n\n<p>The profiling was performed on release compile in a loop of one million times on each method with a random integer input value. Each test was ran more than 10 times and averaged.  The tick results include the total time to execute which will include the random number generation etc. but those will be constant across the tests.  1 tick = 10ns.</p>\n\n<p>Note that the code here isn\'t the complete test code, it is only the basic enum validation method.  There were also a lot of additional variations on these that were tested, and all of them with results similar to those shown here that benched 1,800,000 ticks.</p>\n\n<p>Listed slowest to fastest with rounded results, hopefully no typos.</p>\n\n<p><strong>Bounds determined in Method</strong> = 13,600,000 ticks</p>\n\n<pre><code>public static T Clamp&lt;T&gt;(T value)\n{\n    int minimum = Enum.GetValues(typeof(T)).GetLowerBound(0);\n    int maximum = Enum.GetValues(typeof(T)).GetUpperBound(0);\n\n    if (Convert.ToInt32(value) &lt; minimum) { return (T)Enum.ToObject(typeof(T), minimum); }\n    if (Convert.ToInt32(value) &gt; maximum) { return (T)Enum.ToObject(typeof(T), maximum); }\n    return value;\n}\n</code></pre>\n\n<p><strong>Enum.IsDefined</strong> = 1,800,000 ticks<br>\nNote: this code version doesn\'t clamp to Min/Max but returns Default if out of bounds.</p>\n\n<pre><code>public static T ValidateItem&lt;T&gt;(T eEnumItem)\n{\n    if (Enum.IsDefined(typeof(T), eEnumItem) == true)\n        return eEnumItem;\n    else\n        return default(T);\n}\n</code></pre>\n\n<p><strong>System.Enum Convert Int32 with casts</strong> = 1,800,000 ticks</p>\n\n<pre><code>public static Enum Clamp(this Enum value, Enum minimum, Enum maximum)\n{\n    if (Convert.ToInt32(value) &lt; Convert.ToInt32(minimum)) { return minimum; }\n    if (Convert.ToInt32(value) &gt; Convert.ToInt32(maximum)) { return maximum; }\n    return value;\n}\n</code></pre>\n\n<p><strong>if() Min/Max Constants</strong> = 43,000 ticks = the winner by 42x and 316x faster.</p>\n\n<pre><code>public static MyEnum Clamp(MyEnum value)\n{\n    if (value &lt; MYENUM_MINIMUM) { return MYENUM_MINIMUM; }\n    if (value &gt; MYENUM_MAXIMUM) { return MYENUM_MAXIMUM; }\n    return value;\n}\n</code></pre>\n\n<p>-eol-</p>\n'}, {'answer_id': 19036239, 'author': 'Schultz9999', 'author_id': 494343, 'author_profile': 'https://Stackoverflow.com/users/494343', 'pm_score': 1, 'selected': False, 'text': '<p>This is how I do it based on multiple posts online. The reason for doing this is to make sure enums marked with <code>Flags</code> attribute can also be successfully validated.</p>\n\n<pre><code>public static TEnum ParseEnum&lt;TEnum&gt;(string valueString, string parameterName = null)\n{\n    var parsed = (TEnum)Enum.Parse(typeof(TEnum), valueString, true);\n    decimal d;\n    if (!decimal.TryParse(parsed.ToString(), out d))\n    {\n        return parsed;\n    }\n\n    if (!string.IsNullOrEmpty(parameterName))\n    {\n        throw new ArgumentException(string.Format("Bad parameter value. Name: {0}, value: {1}", parameterName, valueString), parameterName);\n    }\n    else\n    {\n        throw new ArgumentException("Bad value. Value: " + valueString);\n    }\n}\n</code></pre>\n'}, {'answer_id': 21990178, 'author': 'Vman', 'author_id': 299529, 'author_profile': 'https://Stackoverflow.com/users/299529', 'pm_score': 3, 'selected': False, 'text': '<p>This answer is in response to deegee\'s answer which raises the performance issues of System.Enum so should not be taken as my preferred generic answer, more addressing enum validation in tight performance scenarios.</p>\n\n<p>If you have a mission critical performance issue where slow but functional code is being run in a tight loop then I personally would look at moving that code out of the loop if possible instead of solving by reducing functionality. Constraining the code to only support contiguous enums could be a nightmare to find a bug if, for example, somebody in the future decides to deprecate some enum values. Simplistically you could just call Enum.GetValues once, right at the start to avoid triggering all the reflection, etc thousands of times. That should give you an immediate performance increase. If you need more performance and you know that a lot of your enums are contiguous (but you still want to support \'gappy\' enums) you could go a stage further and do something like:</p>\n\n<pre><code>public abstract class EnumValidator&lt;TEnum&gt; where TEnum : struct, IConvertible\n{\n    protected static bool IsContiguous\n    {\n        get\n        {\n            int[] enumVals = Enum.GetValues(typeof(TEnum)).Cast&lt;int&gt;().ToArray();\n\n            int lowest = enumVals.OrderBy(i =&gt; i).First();\n            int highest = enumVals.OrderByDescending(i =&gt; i).First();\n\n            return !Enumerable.Range(lowest, highest).Except(enumVals).Any();\n        }\n    }\n\n    public static EnumValidator&lt;TEnum&gt; Create()\n    {\n        if (!typeof(TEnum).IsEnum)\n        {\n            throw new ArgumentException("Please use an enum!");\n        }\n\n        return IsContiguous ? (EnumValidator&lt;TEnum&gt;)new ContiguousEnumValidator&lt;TEnum&gt;() : new JumbledEnumValidator&lt;TEnum&gt;();\n    }\n\n    public abstract bool IsValid(int value);\n}\n\npublic class JumbledEnumValidator&lt;TEnum&gt; : EnumValidator&lt;TEnum&gt; where TEnum : struct, IConvertible\n{\n    private readonly int[] _values;\n\n    public JumbledEnumValidator()\n    {\n        _values = Enum.GetValues(typeof (TEnum)).Cast&lt;int&gt;().ToArray();\n    }\n\n    public override bool IsValid(int value)\n    {\n        return _values.Contains(value);\n    }\n}\n\npublic class ContiguousEnumValidator&lt;TEnum&gt; : EnumValidator&lt;TEnum&gt; where TEnum : struct, IConvertible\n{\n    private readonly int _highest;\n    private readonly int _lowest;\n\n    public ContiguousEnumValidator()\n    {\n        List&lt;int&gt; enumVals = Enum.GetValues(typeof (TEnum)).Cast&lt;int&gt;().ToList();\n\n        _lowest = enumVals.OrderBy(i =&gt; i).First();\n        _highest = enumVals.OrderByDescending(i =&gt; i).First();\n    }\n\n    public override bool IsValid(int value)\n    {\n        return value &gt;= _lowest &amp;&amp; value &lt;= _highest;\n    }\n}\n</code></pre>\n\n<p>Where your loop becomes something like:</p>\n\n<pre><code>//Pre import-loop\nEnumValidator&lt; MyEnum &gt; enumValidator = EnumValidator&lt; MyEnum &gt;.Create();\nwhile(import)   //Tight RT loop.\n{\n    bool isValid = enumValidator.IsValid(theValue);\n}\n</code></pre>\n\n<p>I\'m sure the EnumValidator classes could written more efficiently (it’s just a quick hack to demonstrate) but quite frankly who cares what happens outside the import loop? The only bit that needs to be super-fast is within the loop. This was the reason for taking the abstract class route, to avoid an unnecessary if-enumContiguous-then-else in the loop (the factory Create essentially does this upfront).\nYou will note a bit of hypocrisy, for brevity this code constrains functionality to int-enums. I should be making use of IConvertible rather than using int\'s directly but this answer is already wordy enough!</p>\n'}, {'answer_id': 27305198, 'author': 'Doug S', 'author_id': 1145177, 'author_profile': 'https://Stackoverflow.com/users/1145177', 'pm_score': 4, 'selected': False, 'text': "<p>As others have mentioned, <code>Enum.IsDefined</code> is slow, something you have to be aware of if it's in a loop.</p>\n\n<p>When doing multiple comparisons, a speedier method is to first put the values into a <code>HashSet</code>. Then simply use <code>Contains</code> to check whether the value is valid, like so:</p>\n\n<pre><code>int userInput = 4;\n// below, Enum.GetValues converts enum to array. We then convert the array to hashset.\nHashSet&lt;int&gt; validVals = new HashSet&lt;int&gt;((int[])Enum.GetValues(typeof(MyEnum)));\n// the following could be in a loop, or do multiple comparisons, etc.\nif (validVals.Contains(userInput))\n{\n    // is valid\n}\n</code></pre>\n"}, {'answer_id': 38331283, 'author': 'Juan Carlos Velez', 'author_id': 391895, 'author_profile': 'https://Stackoverflow.com/users/391895', 'pm_score': 0, 'selected': False, 'text': '<p>To validate if a value is a valid value in an enumeration, you only need to call the static method <a href="https://msdn.microsoft.com/en-us/library/system.enum.isdefined(v=vs.110).aspx" rel="nofollow">Enum.IsDefined</a>.</p>\n\n<pre><code>int value = 99;//Your int value\nif (Enum.IsDefined(typeof(your_enum_type), value))\n{\n   //Todo when value is valid\n}else{\n   //Todo when value is not valid\n}\n</code></pre>\n'}, {'answer_id': 55028274, 'author': 'Timo', 'author_id': 543814, 'author_profile': 'https://Stackoverflow.com/users/543814', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Update 2022-09-27</strong></p>\n<p>As of .NET 5, a fast, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?#system-enum-isdefined-1(-0)" rel="nofollow noreferrer">generic overload</a> is available: <code>Enum.IsDefined&lt;TEnum&gt;(TEnum value)</code>.</p>\n<p>The generic overload alleviates the performance issues of the non-generic one.</p>\n<p><strong>Original Answer</strong></p>\n<p>Here is a fast generic solution, using a statically-constucted <code>HashSet&lt;T&gt;</code>.</p>\n<p>You can define this once in your toolbox, and then use it for all your enum validation.</p>\n<pre><code>public static class EnumHelpers\n{\n    /// &lt;summary&gt;\n    /// Returns whether the given enum value is a defined value for its type.\n    /// Throws if the type parameter is not an enum type.\n    /// &lt;/summary&gt;\n    public static bool IsDefined&lt;T&gt;(T enumValue)\n    {\n        if (typeof(T).BaseType != typeof(System.Enum)) throw new ArgumentException($&quot;{nameof(T)} must be an enum type.&quot;);\n\n        return EnumValueCache&lt;T&gt;.DefinedValues.Contains(enumValue);\n    }\n\n    /// &lt;summary&gt;\n    /// Statically caches each defined value for each enum type for which this class is accessed.\n    /// Uses the fact that static things exist separately for each distinct type parameter.\n    /// &lt;/summary&gt;\n    internal static class EnumValueCache&lt;T&gt;\n    {\n        public static HashSet&lt;T&gt; DefinedValues { get; }\n\n        static EnumValueCache()\n        {\n            if (typeof(T).BaseType != typeof(System.Enum)) throw new Exception($&quot;{nameof(T)} must be an enum type.&quot;);\n\n            DefinedValues = new HashSet&lt;T&gt;((T[])System.Enum.GetValues(typeof(T)));\n        }\n    }\n}\n</code></pre>\n<p>Note that this approach is easily extended to enum parsing as well, by using a dictionary with string keys (minding case-insensitivity and numeric string representations).</p>\n'}, {'answer_id': 56796430, 'author': 'Matt Jenkins', 'author_id': 251200, 'author_profile': 'https://Stackoverflow.com/users/251200', 'pm_score': 2, 'selected': False, 'text': "<p>Building upon Timo's answer, here is an even faster, safer and simpler solution, provided as an extension method.</p>\n<pre><code>public static class EnumExtensions\n{\n    /// &lt;summary&gt;Whether the given value is defined on its enum type.&lt;/summary&gt;\n    public static bool IsDefined&lt;T&gt;(this T enumValue) where T : Enum\n    {\n        return EnumValueCache&lt;T&gt;.DefinedValues.Contains(enumValue);\n    }\n    \n    private static class EnumValueCache&lt;T&gt; where T : Enum\n    {\n        public static readonly HashSet&lt;T&gt; DefinedValues = new HashSet&lt;T&gt;((T[])Enum.GetValues(typeof(T)));\n    }\n}\n</code></pre>\n<p><strong>Usage:</strong></p>\n<pre><code>if (myEnumValue.IsDefined()) { ... }\n</code></pre>\n<p><strong>Update - it's even now cleaner in .NET 5:</strong></p>\n<pre><code>public static class EnumExtensions\n{\n    /// &lt;summary&gt;Whether the given value is defined on its enum type.&lt;/summary&gt;\n    public static bool IsDefined&lt;T&gt;(this T enumValue) where T : struct, Enum\n    {\n        return EnumValueCache&lt;T&gt;.DefinedValues.Contains(enumValue);\n    }\n\n    private static class EnumValueCache&lt;T&gt; where T : struct, Enum\n    {\n        public static readonly HashSet&lt;T&gt; DefinedValues = new(Enum.GetValues&lt;T&gt;());\n    }\n}\n</code></pre>\n"}, {'answer_id': 59470338, 'author': 'Cemal', 'author_id': 12493422, 'author_profile': 'https://Stackoverflow.com/users/12493422', 'pm_score': 1, 'selected': False, 'text': '<p>You can use the FluentValidation for your project. Here is a simple example for the "Enum Validation"</p>\n\n<p>Let\'s create a EnumValidator class with using FluentValidation;</p>\n\n<pre><code>public class EnumValidator&lt;TEnum&gt; : AbstractValidator&lt;TEnum&gt; where TEnum : struct, IConvertible, IComparable, IFormattable\n{\n    public EnumValidator(string message)\n    {\n        RuleFor(a =&gt; a).Must(a =&gt; typeof(TEnum).IsEnum).IsInEnum().WithMessage(message);\n    }\n\n}\n</code></pre>\n\n<p>Now we created the our enumvalidator class; let\'s create the a class to call enumvalidor class;</p>\n\n<pre><code> public class Customer \n{\n  public string Name { get; set; }\n  public Address address{ get; set; }\n  public AddressType type {get; set;}\n}\npublic class Address \n{\n  public string Line1 { get; set; }\n  public string Line2 { get; set; }\n  public string Town { get; set; }\n  public string County { get; set; }\n  public string Postcode { get; set; }\n</code></pre>\n\n<p>}</p>\n\n<pre><code>public enum AddressType\n{\n   HOME,\n   WORK\n}\n</code></pre>\n\n<p>Its time to call our enum validor for the address type in customer class.</p>\n\n<pre><code>public class CustomerValidator : AbstractValidator&lt;Customer&gt;\n{\n    public CustomerValidator()\n   {\n     RuleFor(x =&gt; x.type).SetValidator(new EnumValidator&lt;AddressType&gt;("errormessage");\n  }\n}\n</code></pre>\n'}, {'answer_id': 71877470, 'author': 'Christopher Eberle', 'author_id': 15324778, 'author_profile': 'https://Stackoverflow.com/users/15324778', 'pm_score': 1, 'selected': False, 'text': "<p>To expound on the performance scaling specifically regarding Timo/Matt Jenkins method:\nConsider the following code:</p>\n<pre><code>//System.Diagnostics - Stopwatch\n//System - ConsoleColor\n//System.Linq - Enumerable\nStopwatch myTimer = Stopwatch.StartNew();\nint myCyclesMin = 0;\nint myCyclesCount = 10000000;\nlong myExt_IsDefinedTicks;\nlong myEnum_IsDefinedTicks;\nforeach (int lCycles in Enumerable.Range(myCyclesMin, myCyclesMax))\n{\n    Console.WriteLine(string.Format(&quot;Cycles: {0}&quot;, lCycles));\n\n    myTimer.Restart();\n    foreach (int _ in Enumerable.Range(0, lCycles)) { ConsoleColor.Green.IsDefined(); }\n    myExt_IsDefinedTicks = myTimer.ElapsedTicks;\n\n    myTimer.Restart();\n    foreach (int _ in Enumerable.Range(0, lCycles)) { Enum.IsDefined(typeof(ConsoleColor), ConsoleColor.Green); }\n    myEnum_IsDefinedTicks = myTimer.E\n\n    Console.WriteLine(string.Format(&quot;object.IsDefined() Extension Elapsed: {0}&quot;, myExt_IsDefinedTicks.ToString()));\n    Console.WriteLine(string.Format(&quot;Enum.IsDefined(Type, object): {0}&quot;, myEnum_IsDefinedTicks.ToString()));\n    if (myExt_IsDefinedTicks == myEnum_IsDefinedTicks) { Console.WriteLine(&quot;Same&quot;); }\n    else if (myExt_IsDefinedTicks &lt; myEnum_IsDefinedTicks) { Console.WriteLine(&quot;Extension&quot;); }\n    else if (myExt_IsDefinedTicks &gt; myEnum_IsDefinedTicks) { Console.WriteLine(&quot;Enum&quot;); }\n}\n</code></pre>\n<p>Output starts out like the following:</p>\n<pre><code>Cycles: 0\nobject.IsDefined() Extension Elapsed: 399\nEnum.IsDefined(Type, object): 31\nEnum\nCycles: 1\nobject.IsDefined() Extension Elapsed: 213654\nEnum.IsDefined(Type, object): 1077\nEnum\nCycles: 2\nobject.IsDefined() Extension Elapsed: 108\nEnum.IsDefined(Type, object): 112\nExtension\nCycles: 3\nobject.IsDefined() Extension Elapsed: 9\nEnum.IsDefined(Type, object): 30\nExtension\nCycles: 4\nobject.IsDefined() Extension Elapsed: 9\nEnum.IsDefined(Type, object): 35\nExtension\n</code></pre>\n<p>This seems to indicate there is a steep setup cost for the static hashset object (in my environment, approximately 15-20ms.\nReversing which method is called first doesn't change that the first call to the extension method (to set up the static hashset) is quite lengthy. <code>Enum.IsDefined(typeof(T), object)</code> is also longer than normal for the first cycle, but, interestingly, much less so.</p>\n<p>Based on this, it appears <code>Enum.IsDefined(typeof(T), object)</code> is actually faster until <code>lCycles = 50000</code> or so.</p>\n<p>I'm unsure why <code>Enum.IsDefined(typeof(T), object)</code> gets faster at both 2 and 3 lookups before it starts rising. Clearly there's some process going on internally as <code>object.IsDefined()</code> also takes markedly longer for the first 2 lookups before settling in to be bleeding fast.</p>\n<p>Another way to phrase this is that if you need to lots of lookups with any other remotely long activity (perhaps a file operation like an open) that will add a few milliseconds, the initial setup for <code>object.IsDefined()</code> will be swallowed up (especially if async) and become mostly unnoticeable. At that point, <code>Enum.IsDefined(typeof(T), object)</code> takes roughly 5x longer to execute.</p>\n<p>Basically, if you don't have literally thousands of calls to make for the same Enum, I'm not sure how hashing the contents is going to save you time over your program execution. <code>Enum.IsDefined(typeof(T), object)</code> may have conceptual performance problems, but ultimately, it's fast enough until you need it thousands of times for the same enum.</p>\n<p>As an interesting side note, implementing the ValueCache as a hybrid dictionary yields a startup time that reaches parity with <code>Enum.IsDefined(typeof(T), object)</code> within ~1500 iterations. Of course, using a HashSet passes both at ~50k.</p>\n<p>So, my advice: If your entire program is validating the same enum (validating different enums causes the same level of startup delay, once for each different enum) less than 1500 times, use <code>Enum.IsDefined(typeof(T), object)</code>. If you're between 1500 and 50k, use a HybridDictionary for your hashset, the initial cache populate is roughly 10x faster. Anything over 50k iterations, HashSet is a pretty clear winner.</p>\n<p>Also keep in mind that we are talking in Ticks. In .Net a 10,000 ticks is 1 ms.</p>\n<p>For full disclosure I also tested List as a cache, and it's about 1/3 the populate time as hashset, however, for any enum over 9 or so elements, it's way slower than any other method. If all your enums are less than 9 elements, (or smaller yet) it may be the fastest approach.</p>\n<p>The cache defined as a HybridDictionary (yes, the keys and values are the same. Yes, it's quite a bit harder to read than the simpler answers referenced above):</p>\n<pre><code>//System.Collections.Specialized - HybridDictionary\nprivate static class EnumHybridDictionaryValueCache&lt;T&gt; where T : Enum\n        {\n            static T[] enumValues = (T[])Enum.GetValues(typeof(T));\n\n            static HybridDictionary PopulateDefinedValues()\n            {\n                HybridDictionary myDictionary = new HybridDictionary(enumValues.Length);\n                foreach (T lEnumValue in enumValues)\n                {\n                    //Has to be unique, values are actually based on the int value. Enums with multiple aliases for one value will fail without checking.\n                    //Check implicitly by using assignment.\n                    myDictionary[lEnumValue] = lEnumValue;\n                }\n                return myDictionary;\n            }\n\n            public static readonly HybridDictionary DefinedValues = PopulateDefinedValues();\n        }\n\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/13615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1154/']