title: Cast Int to Generic Nullable Enum in C#
body: <p>I would like to cast an int value as nullable enum used a generic function.  I thought it would be easy, especially with all the with all the SO about the enum / int casting.  The closest question I've found is <a href="https://stackoverflow.com/questions/10387095/cast-int-to-generic-enum-in-c-sharp">this one</a>, but unfortunately, it doesn't handle the nullable enums.  <a href="https://stackoverflow.com/questions/5199419/c-sharp-cast-object-of-type-int-to-nullable-enum">This question</a> solve the Nullable enums casting question but not with the generic.</p>
  
  <p>Here's a simplified example of what I'm trying to do:</p>
  
  <pre><code>public enum SouthParkCharacters
  {
      Stan = 0,
      Kyle = 1,
      Eric = 2,
      Kenny = 3
  }
  
  public static T CastNullableEnum&lt;T&gt;(int value)
  {
      return (T)(object)((int?)value).Value;
  }
  
  
  public static T SomeFunction&lt;T&gt;(this int anyEnumValue)
  {
          SouthParkCharacters? spc = SouthParkCharacters.Kenny;
  
          spc = CastNullableEnum&lt;SouthParkCharacters&gt;(3); //I am working!
          spc = CastNullableEnum&lt;SouthParkCharacters?&gt;(3); //Raise error Specified cast is not valid.
  
          //This function will be public so I won't have control over the T
          T finalValue = CastNullableEnum&lt;T&gt;(anyEnumValue); //Raise error Specified cast is not valid.
  
          return finalValue;
  
  }
  </code></pre>
  
  <p>As you can see in last function, a cast for a non-nullable enum is working.  The problem is that I want to be able to call the CastNullableEnum from an other generic function, which could use a nullable enum as a generic type.</p>
  
  <p>I know you can pass a generic type as a nullable generic <code>CastNullableEnum&lt;T?&gt;</code> but can we do the opposite (i.e. pass the nullable underlying type to generic function)?</p>
  
  <p>If this can't be done, then I guess the solution would be to find the right way to cast an enum value in the CastNullableEnum function.</p>