title: C# how to have multiple constraints on the same type
body: <p>I was identified a pattern of using <code>IDisposable</code> and would like to write the following code to generise it:</p>
  
  <pre><code>public static void SetTo&lt;T&gt;(this T value, ref T pos) where T : IDisposable
  {
      using (var _ = Interlocked.Exchange(ref pos, value))
      {
      }
  }
  </code></pre>
  
  <p>However this didn't compile, nor can I do</p>
  
  <pre><code>public static void SetTo&lt;T&gt;(this T value, ref T pos) where T : IDisposable where T : class
  {
      using (var _ = Interlocked.Exchange(ref pos, value))
      {
      }
  }
  </code></pre>
  
  <p>Actually I only use this when T is a class (not value type), but <code>IDisposable</code> supports value type as well so the class constraint is not enough.</p>
  
  <p>How can I specify both <code>IDisposable</code> and <code>class</code> constraint?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Thanks for the answer. I have also updated the title. There are suggestion that I shall check that <code>pos</code> and <code>value</code> are not the samething. Such a check can be done as following:</p>
  
  <pre><code>public static void SetTo&lt;T&gt;(this T value, ref T pos) where T : class,  IDisposable
  {
      for (;;)
      {
          var old = pos;
          if (ReferenceEquals(value, old))
              return;
          if (Interlocked.CompareExchange(ref pos, value, old) != old) 
              continue;
          using (old)
             return;
      }
  }
  </code></pre>