Just looking through the LINQ tutorials on MSDN and come accross the following code:
IEnumerable<int> numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;
I don’t understand how an interface is being returned? It was my understanding that an interface is simply an outline for a class, and certainly cannot contain any data.
I would love this to be cleared up.
The interface is a contract on the return value: Linq won’t actually tell you what it will return (as in the actual class), but it will guarantee that it behaves like an
IEnumerable<int>, that is, the class it returns implements this interface. It could be aList<int>or aWhackyLinqInternalEnumerable<int>– but you don’t really care, because, well, all you’re interested in is the interface (what you can do with the object).One thing that might be confusing you is the difference between a variable and the object it represents: For (reference) types, the variable just “points” to the object. You can have a lot of variables “pointing” to the same object. They don’t need to have the same type, but the object they all point to must be either of the same type as the variable, a subtype or (in the case of a variable with an interface type) must implement the same variable.