title: C# Casting with objects to Enums
body: <p>This question relates to casting of enums within generic methods</p>
  
  <p>Given an enum</p>
  
  <pre><code>public enum Crustaceans
  {
      Frog = 1,
      Toad = 4
  }
  </code></pre>
  
  <p>I can create an instance of my enum simply enough</p>
  
  <pre><code>short val = 4;
  Crustaceans crusty = (Crustaceans) val;
  </code></pre>
  
  <p>However, if</p>
  
  <pre><code>short val = 4;
  object obj = (object) val;
  Crustaceans crusty = (Crustaceans)obj;
  </code></pre>
  
  <p>a runtime exception is thrown attempting to perform the initialisation of crusty.</p>
  
  <p>Can anyone explain why this is happening, and why it is not legal to do such a thing.</p>
  
  <p>Not that I really wanted to do this, but I cam across an issue when trying to get something similar happening with generics and effectively that is what is happening under the covers.  i.e.</p>
  
  <pre><code>public T dosomething&lt;T&gt;(short val) where T : new()
  {
      T result = (T)(object) val;
      return result;
  }
  </code></pre>
  
  <p>So what I am attempting to do is have a generic function that works with enums and non-enums (not so critical-but would be nice) that can be set to a short value without throwing an exception and actually initialising the correct enum value.</p>