title: Cast Int to Generic Enum in C#
body: <p>Similar to <a href="https://stackoverflow.com/questions/29482/cast-int-to-enum-in-c-sharp">Cast int to enum in C#</a> but my enum is a Generic Type parameter.  What is the <em>best</em> way to handle this?</p>
  
  <p>Example:</p>
  
  <pre><code>private T ConvertEnum&lt;T&gt;(int i) where T : struct, IConvertible
  {
      return (T)i;
  }
  </code></pre>
  
  <p>Generates compiler error <code>Cannot convert type 'int' to 'T'</code></p>
  
  <p>Full code is as follows, where value can contain the int, or null.</p>
  
  <pre><code>private int? TryParseInt(string value)
  {
      var i = 0;
      if (!int.TryParse(value, out i))
      {
          return null;
      }
      return i;
  }
  
  private T? TryParseEnum&lt;T&gt;(string value) where T : struct, IConvertible
  {
      var i = TryParseInt(value);
      if (!i.HasValue)
      {
          return null;
      }
  
      return (T)i.Value;
  }
  </code></pre>