title: InvalidCastException trying to cast from a boxed int to a nullable enum
body: <p>I have an enum, <code>Foo</code>:</p>
  
  <pre><code>public enum Foo { Alpha, Bravo, Charlie }
  </code></pre>
  
  <p>If I attempt the following cast from a boxed <code>int</code> to a <code>Foo?</code>, I get an <code>InvalidCastException</code>:</p>
  
  <pre><code>var x = (Foo?)(object)1;
  </code></pre>
  
  <p>This led me to some experimentation...</p>
  
  <pre><code>var x = (Foo)(object)1; // succeeds
  var x = (long)(object)1; // fails
  var x = (long?)(object)1; // fails
  var x = (long)1; // succeeds
  var x = (long?)1; // succeeds
  var x = (int)(object)1; // succeeds
  var x = (int?)(object)1; // succeeds
  </code></pre>
  
  <p>What this tells me is that you can cast from a boxed <code>int</code> to an enum but not to a <code>long</code>, and you <em>cannot</em> convert from a boxed <code>int</code> to any kind of nullable except an <code>int?</code>.</p>
  
  <p>By the way, the reason I'm casting the <code>int</code> to <code>object</code> first is that I'm really trying to cast from an <code>int</code> to a generic parameter <code>TValue</code>, like this:</p>
  
  <pre><code>var x = (TValue)(object)1;
  </code></pre>
  
  <p>If I didn't have <code>(object)</code>, it wouldn't compile. (See this <a href="http://blogs.msdn.com/b/ericlippert/archive/2012/07/10/when-is-a-cast-not-a-cast.aspx" rel="nofollow">blog post by Eric Lippert</a> for details.)</p>
  
  <p><strong>Questions</strong></p>
  
  <ol>
  <li><p>Why can you convert from a boxed <code>int</code> to an enum, but not to a nullable enum (and not to a <code>long</code> nor a <code>long?</code>)?</p></li>
  <li><p>What's the easiest way to rewrite <code>var x = (TValue)(object)1;</code> so that it compiles, works at runtime, and is performant (assuming <code>TValue</code> is determined to be a <code>Foo?</code> at runtime)?</p></li>
  </ol>