title: C# Generic and Specific Extension Method Combination Ambiguity
body: <p>I have an <em>abstract class</em> called <strong>Fruit.</strong>
  I then have a <em>derived class</em> called <strong>Apple</strong>.</p>
  
  <p>I have these two extension methods:</p>
  
  <pre><code>public static IQueryable&lt;TFruit&gt; WithEagerLoading&lt;TFruit&gt;(this IQueryable&lt;TFruit&gt; query) where TFruit : Fruit
  {
     return query.EagerLoad(x =&gt; x.Distributors); // Fruit.Distributors
  }
  
  public static IQueryable&lt;Apple&gt; WithEagerLoading(this IQueryable&lt;Apple&gt; query)
  {
     query = query.EagerLoad(x =&gt; x.AppleBrands); // Apple.AppleBrands
  
     // now bubble up to base extension method
     return query.WithEagerLoading&lt;Apple&gt;();
  }
  </code></pre>
  
  <p>Now, here is the generic method i have in a Repository:</p>
  
  <pre><code>public TFruit FindById&lt;TFruit&gt;(int fruitId) where TFruit : Fruit
  {
     var query = _ctx.Fruits // IQueryable&lt;Fruit&gt;
                     .OfType&lt;TFruit&gt;(); // IQueryable&lt;TFruit&gt;
  
     query = query.WithEagerLoading();
  
     return query.SingleOrDefault(x =&gt; x.FruitId == fruitId);
  }
  </code></pre>
  
  <p>The problem i have, is when i do this:</p>
  
  <pre><code>var apple = repository.FindById&lt;Apple&gt;(1);
  </code></pre>
  
  <p>It goes into the <code>IQueryable&lt;Fruit&gt;</code> extension method.</p>
  
  <p>I want it to go into <code>IQueryable&lt;Apple&gt;</code> extension method. For other types of Fruit, it should go into the <code>IQueryable&lt;TFruit&gt;</code> extension method.</p>
  
  <p>I thought the compiler would pick the most specific extension method.</p>
  
  <p>Any ideas?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Thanks for the comments/answer. I see now why this doesn't work.</p>
  
  <p>So what are options to resolve this? If i create a method:</p>
  
  <p><code>public static IQueryable&lt;Apple&gt; WithAppleEagerLoading(this IQueryable&lt;Apple&gt; query)</code></p>
  
  <p>How would i call it from my generic repository? I would have to inspect the type of <code>TFruit</code>:</p>
  
  <pre><code>public TFruit FindById&lt;TFruit&gt;(int fruitId) where TFruit : Fruit
  {
     var query = _ctx.Fruits // IQueryable&lt;Fruit&gt;
                     .OfType&lt;TFruit&gt;(); // IQueryable&lt;TFruit&gt;
  
     if (typeof(TFruit) == typeof(Apple))
         query = query.WithAppleEagerLoading();
     else 
         query = query.WithEagerLoading();
  
     return query.SingleOrDefault(x =&gt; x.FruitId == fruitId);
  }
  </code></pre>
  
  <p>Which isn't nice - considering i have around 20 derived types.</p>
  
  <p>Can anyone offer an alternative as to what i'm attempting to do?</p>