title: Is it possible to have a generic constraint requiring an open generic interface?
body: <p>I'm implementing a repository and keep wondering about making it a bit more friendly to the user. Right now I have an <code>IEntity</code> interface that specifies an <code>Id</code> field:</p>
  
  <pre><code>public interface IEntity&lt;T&gt;
  {
      T Id { get; set; }
  }
  </code></pre>
  
  <p>And my repository allows users to get an new instance by that id. Now the types it can handle need to implement the <code>IEntity</code> interface, so I have a generic constraint on the repository <code>Get</code> method:</p>
  
  <pre><code>public class Repository
  {
      public T Get&lt;T, U&gt;(U id) where T: IEntity&lt;U&gt;
      {
          // fake implementation, but T is required at compile time
          var result = Activator.CreateInstance&lt;T&gt;();
          result.Id = id;
          return result;
      }
  }
  </code></pre>
  
  <p>There's an obvious relation between <code>T</code> and <code>U</code> and compiler understands it well enough to flag miss-usages, but not enough to enable type inference - each call to <code>Get</code> requires specifying the generic parameters explicitly. I know there's no way around specifying <code>T</code>, but how can I improve the method signature so that specifying <code>U</code> is not required? Right now I have an overload for the most common usage:</p>
  
  <pre><code>public T Get&lt;T&gt;(int id) where T : IEntity&lt;int&gt;
  {
      return Get&lt;T, int&gt;(id);
  }
  </code></pre>
  
  <p>I'm wondering if it is possible to somehow specify an open generic interface as a constraint or what would be a better method signature for the general case.</p>