When using an EF ObjectContext
I see two different extensions methods with the same signature as consecutive choices. It doesn't makes sense to me that there would be some magic that caused one or the other to get called based on which one I picked, so what is actually going on?

- 3,360
- 23
- 28

- 16,906
- 15
- 62
- 121
-
4One of them returns an `IQueryable`, the other returns an `IEnumerable`. – Robert Harvey Jul 07 '12 at 22:59
-
but they both return a `Campaign`, don't they? I could be totally missing something in which case I apologize up front... – Aaron Anodide Jul 07 '12 at 23:10
-
1Right, they both return a Campaign. One is an extension method for an IQueryable
and the other is an extension method for IEnumerable – Bob Horn Jul 07 '12 at 23:17. -
1its not the end of the world if the answer to a question is clarifying the underlying confusion that caused it to be asked – Aaron Anodide Jul 07 '12 at 23:24
1 Answers
I'm assuming that Campaigns
is an instance of DbSet<Campaign>
? DbSet
inherits DbQuery
, which implements IOrderedQueryable
, the definition for which is:
public interface IOrderedQueryable<out T> : IQueryable<T>,
IEnumerable<T>, IOrderedQueryable, IQueryable, IEnumerable
As you can see, both IQueryable<T>
and IEnumerable<T>
are implemented, but the definition of IQueryable
shows that it extends IEnumerable
:
public interface IQueryable : IEnumerable
So basically, the extension method is implemented for IEnumerable
, but it's also available from IQueryable
as it extends the original interface. Intellisense is picking up both of these options because you could end up implicitly or explicitly casting the type to an IEnumerable
.
The method that will actually be run will depend on the type on which it's called. For example, on your Campaigns
instance of DbSet<Campaign>
the method will translate it (if you're using MS SQL) into a SELECT TOP 1...
query, but if you're calling it on Campaigns.ToList()
, which is IEnumerable
, it'll return the item at the zero index. The implementation of the extension methods are different for each type.
Hope that makes sense :)

- 7,541
- 3
- 36
- 45
-
yes, that makes sense, thank you (it's ObjectSet but I bet your answer is right nonetheless) – Aaron Anodide Jul 07 '12 at 23:22
-
Ah ok, `ObjectSet` implements `IEnumerable` and `IQueryable` directly, so it's pretty much the same, just ignore the first paragraph and `IOrderedQueryable` definition. See http://msdn.microsoft.com/en-us/library/dd412719.aspx – greg84 Jul 07 '12 at 23:25
-
This also might be a useful read: http://stackoverflow.com/questions/252785/what-is-the-difference-between-iqueryablet-and-ienumerablet – greg84 Jul 07 '12 at 23:26