title: Can I cast from a generic type to an enum in C#?
body: <p>I'm writing an utility function that gets a integer from the database and returns a typed enum to the application.</p>
  
  <p>Here is what I tried to do (note I pass in a data reader and column name instead of the <code>int</code> in my real function):</p>
  
  <pre><code>public static T GetEnum&lt;T&gt;(int enumAsInt)
  {
      Type enumType = typeof(T);
  
      Enum value = (Enum)Enum.ToObject(enumType, enumAsInt);
      if (Enum.IsDefined(enumType, value) == false)
      {
          throw new NotSupportedException("Unable to convert value from database to the type: " + enumType.ToString());
      }
  
      return (T)value;
  }
  </code></pre>
  
  <p>But it won't let me cast <code>(T)value</code> saying: </p>
  
  <blockquote>
    <p>Cannot convert type 'System.Enum' to 'T'.</p>
  </blockquote>
  
  <p>Also I've read quite a bit of mixed reviews about using <code>Enum.IsDefined</code>. Performance wise it sounds very poor.  How else can I guarantee a valid value?</p>