Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension methods resolution IQueryable vs IEnumerable

Tags:

c#

.net

Suppose I have a class which implements IQueryable<> (which inherits IEnumerable<>) interface.

When I call Where() method on it, compiler resolves this call to IQueryable extensions although IEnumerable extensions also has Where() method defined.

The question is how the compiler understands which extension should be called?

like image 934
Markus Avatar asked Aug 20 '14 05:08

Markus


People also ask

What is the difference between IQueryable and IEnumerable?

Thanks to LINQ, there’s almost no difference in how we construct queries against these two interfaces. To make it even more confused, IQueryable implements IEnumerable, and thus, results can be enumerated the same way regardless of which interface in use.

What are the advantages of IEnumerable?

IEnumerable is best to query data from in-memory collections like List, Array, etc. While query data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data. IEnumerable is suitable for LINQ to Object and LINQ to XML queries. IEnumerable supports deferred execution.

What is IQueryable in SQL Server?

IQueryable – intended to be run against a “queryable” collection (ex. a database). Lets take the following examples. When we have an in memory list, this Where LINQ statement is defined on the IEnumerable interface.

What is the difference between IQueryable and LINQ?

IQueryable is best to query data from out-memory (like remote database, service) collections. While query data from a database, IQueryable execute the select query on the server side with all filters. IQueryable is suitable for LINQ to SQL queries. IQueryable supports deferred execution.


1 Answers

C# spec has it described:

7.5.3.5 Better conversion target

Given two different types T1 and T2, T1 is a better conversion target than T2 if at least one of the following holds:

  • An implicit conversion from T1 to T2 exists, and no implicit conversion from T2 toT1 exists

  • T1 is a signed integral type and T2 is an unsigned integral type.

Because there is a implicit conversion from IQueryable<T> to IEnumerable<T>, and there is no implicit conversion from IEnumerable<T> to IQueryable<T>, IQueryable<T> is a better conversion target, and takes precedence.

like image 160
MarcinJuraszek Avatar answered Oct 22 '22 00:10

MarcinJuraszek