title: Casting generic type "as T" whilst enforcing the type of T
body: <p>I'm missing a trick here I think and can't believe I've never done this before. However, how can I cast a generic type using the as keyword?</p>
  
  <pre><code>[Serializable]
  public abstract class SessionManager&lt;T&gt; where T : ISessionManager
  {
  
      protected SessionManager() { }
  
      public static T GetInstance(HttpSessionState session)
      {
  
          // Ensure there is a session Id
          if (UniqueId == null)
          {
              UniqueId = Guid.NewGuid().ToString();
          }
  
          // Get the object from session
          T manager = session[UniqueId] as T;
          if (manager == null)
          {
              manager = Activator.CreateInstance&lt;T&gt;();
              session[UniqueId] = manager;
          }
  
          return manager;
  
      }
  
      protected static string UniqueId = null;
  
  }
  </code></pre>
  
  <p>The line <code>T manager = session[UniqueId] as T;</code> throws the following error:</p>
  
  <blockquote>
    <p>The type parameter 'T' cannot be used
    with the 'as' operator because it does
    not have a class type constraint nor a
    'class' constraint</p>
  </blockquote>
  
  <p>Now, I think understand the reason for this; I've not physically told the compiler that T is a class. If I replace:</p>
  
  <pre><code>public abstract class SessionManager&lt;T&gt; where T : ISessionManager
  </code></pre>
  
  <p>with</p>
  
  <pre><code>public abstract class SessionManager&lt;T&gt; where T : class
  </code></pre>
  
  <p>... then the code builds successfully.</p>
  
  <p>But my question is thus; how can I have both the class and ISessionManager enforcements on the generic type? I'm hoping there's a very simple answer for this.</p>
  
  <p><strong>EDIT:</strong>
  Just to add I had tried: <code>where T : ISessionManager, class</code>, turns out I hadn't read my compiler error properly. Simply enough, just putting class before <code>ISessionManager</code> fixes the issue. The error I hadn't read was:</p>
  
  <blockquote>
    <p>"The 'class' or 'struct' constraint
    must come before any other
    constraints". </p>
  </blockquote>
  
  <p>Dumb moment over.</p>