Search code examples
c#linqienumerableenumerable

Why Enumerable doesn't inherits from IEnumerable<T>


I'm very confused about this issue and can't understand it.In the Enumerable Documentation, I read this:

that implement System.Collections.Generic.IEnumerable

and some methods like Select() return IEnumerable<TSource> that we can use from other methods like Where() after using that.for example:

names.Select(name => name).Where(name => name.Length > 3 );

but Enumerable doesn't inherit from IEnumerable<T> and IEnumerable<T> doesn't contain Select(),Where() and etc too...

have i wrong ?
or exists any reason for this?


Solution

  • The Select(), Where() etc are "extension methods". They need to be defined "elsewhere" as an interface can't supply an implementation of methods.

    You can recognize extension methods by the keyword "this" in the argument list. For instance:

    public static IEnumerable<TSource> Where<TSource>(
        this IEnumerable<TSource> source,
        Func<TSource, bool> predicate
    )
    

    can be used as if it's a method on an IEnumerable<TSource> with one parameter: Func<TSource, bool> predicate.