Search code examples
c#linqinterfaceinstantiation

How LINQ returns IEnumerable<T> if interface cannot be instantiated?


I have the following method:

   public IEnumerable<T> Filter(IEnumerable<T> products, ISpecification<T> specification)
    {
        return products.Where(specification.IsFulfilled);

    }

Everything works fine, but after writing this method I started to wonder - how does LINQ return IEnumerable if interfaces cannot be instantiated? Would I be able to return this IEnumerable in another way? Probably I could use foreach and yield, but again I don't understand why I am able to return IEnumerable this way. What am I missing?


Solution

  • You can return a reference to an interface and have variables of the interface since somewhere there is going to be a class that implements the interface. LINQ will return an internal class that implements IEnumerable you will just never know what it is, not should you.