title: How do I specify a constraint that says "collection of nullable types"?
body: <p>I'm trying to create a generic argument-validation method that checks collection parameters for null, empty, or <strong>contains a null element</strong>.</p>
  
  <pre><code>public void Foo(ICollection&lt;MyType&gt; bar)
  {
      // Validate parameters
      ThrowIfNullEmptyOrContainsNull(bar, "bar");
                    .
                    .
                    .
  </code></pre>
  
  <p>If I only specify <code>ICollection&lt;T&gt;</code> in the type constraint, then <code>if (value.Contains(null))</code> generates an error, since <code>T</code> may not be a nullable type.</p>
  
  <p>This was what I came up with, but it doesn't seem to be right:</p>
  
  <pre><code>internal static T1 ThrowIfNullEmptyOrContainsNull&lt;T1, T2&gt;(T1 value, string name)
      where T1 : ICollection&lt;T2&gt;
      where T2 : class
  {
      if (ReferenceEquals(value, null))
          throw new ArgumentNullException(name);
  
      if (value.Count == 0)
          throw new ArgumentException("Empty collection not allowed", name);
  
      if (value.Contains(null))
          throw new ArgumentException("Collection contains one or more null elements", name);
  
      return value;
  }
  </code></pre>
  
  <p>...but then I have to call the method with explicit argument types, something like this:</p>
  
  <pre><code>public void Foo(ICollection&lt;MyType&gt; bar)
  {
      // Validate parameters
      ThrowIfNullEmptyOrContainsNull&lt;(ICollection&lt;MyType&gt;, MyType&gt;(bar, "bar");
                    .
                    .
                    .
  </code></pre>
  
  <p>Without explicitly specifying T1 and T2 in the call, I get an error "The type arguments ... cannot be inferred from the usage".</p>
  
  <p>Can anyone shed light on how to do this?</p>