Note that there are some explanatory texts on larger screens.

plurals
  1. POIf I cast an IQueryable as an IEnumerable then call a Linq extension method, which implementation gets called?
    primarykey
    data
    text
    <p>Considering the following code:</p> <pre><code>IQueryable&lt;T&gt; queryable; // something to instantiate queryable var enumerable = (IEnumerable&lt;T&gt;) queryable; var filtered = enumerable.Where(i =&gt; i &gt; 3); </code></pre> <p>In the final line, which extension method gets called? </p> <p>Is it <code>IEnumerable&lt;T&gt;.Where(...)</code>? Or will <code>IQueryable&lt;T&gt;.Where(...)</code> be called because the actual implementation is still obviously a queryable?</p> <p>Presumably the ideal would be for the IQueryable version to be called, in the same way that normal polymorphism will always use the more specific override.</p> <p>In Visual Studio though when I right-click on the Where method and "Go to Definition" I'm taken to the IEnumerable version, which kind of makes sense from a visual point-of-view.</p> <p>My main concern is that if somewhere in my app I use Linq to NHibernate to get a Queryable, but I pass it around using an interface that uses the more general IEnumerable signature, I'll lose the wonders of deferred database execution!</p> <hr> <p>Edit: It turns out that, as Iridium has pointed out, it's the Enumerable version that gets called</p> <pre><code>public class Program { static void Main(string[] args) { var myString2 = new MyString2(); var myString = (MyString)myString2; Console.WriteLine(myString.Method()); Console.ReadLine(); } } public class MyString {} public class MyString2 : MyString {} public static class ExtensionMethods { public static string Method(this MyString instance) { return "MyString method"; } public static string Method(this MyString2 instance) { return "MyString2 method"; } } </code></pre> <p>The output is "MyString method".</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload