title: c# method in generic class only for certain types
body: <p>I'm trying to define a method on a generic class that is limited to a specific type. I have come up with this:</p>
  
  <pre><code>interface IHasId 
  {
      int Id { get; }
  }
  
  public class Foo&lt;T&gt;
  {
      private List&lt;T&gt; children;
  
      public IHasId GetById(int id)
      {
          foreach (var child in children.Cast&lt;IHasId&gt;())
          {
              if (child.Id == id)
              {
                  return child;
              }
          }
  
          return null;
      }
  }
  </code></pre>
  
  <p>It will work, but it looks like a code smell...it seems like there should be a way to get the compiler to enforce this. Something like:</p>
  
  <pre><code>public class Foo&lt;T&gt;
  {
      public IHasId GetById&lt;TWithId&gt;(int id) where TWithId : IHasId {}
  }
  </code></pre>
  
  <p>or, even better:</p>
  
  <pre><code>public class Foo&lt;T&gt;
  {
      public IHasId GetById(int id) where T : IHasId {}
  }
  </code></pre>
  
  <p>I saw a few posts on this related to Java, and one talking specifically about constraining T to an enum, but nothing directly on point.</p>