title: Ways to cast objects to a generic type
body: <p>In relation to <a href="https://stackoverflow.com/questions/1721741/casting-generic-type-as-t-whilst-enforcing-the-type-of-t">Casting generic type &quot;as T&quot; whilst enforcing the type of T</a></p>
  
  <p>And with the following example</p>
  
  <pre><code>private static T deserialize&lt;T&gt;(string streng) where T : class
  {
      XmlSerializer ser = new XmlSerializer(typeof(T));
      StringReader reader = new StringReader(streng);
      return ser.Deserialize(reader) as T;
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>private static T deserialize&lt;T&gt;(string streng)
  {
      XmlSerializer ser = new XmlSerializer(typeof(T));
      StringReader reader = new StringReader(streng);
      return (T)ser.Deserialize(reader);
  }
  </code></pre>
  
  <p>I'm used to doing the <code>object as Type</code> casting, so I was a little confused when I found that I couldn't just do that with <code>T</code>. Then I found the question above and in that a solution to the <code>as T</code> compiler error.</p>
  
  <p>But why is <code>where T : class</code> necessary when using <code>object as T</code> and not when using <code>(T)object</code>?
  What is the actual difference between the two ways of casting the object?</p>