Reputation: 59
Here is my program :
static void Main(string[] args)
{
int[] myArr = new int[] { 4,6,2,1};
//call Where() linq method
var myEvenNumbers = myArr.Where(n => n % 2 == 0 );
Console.Read();
}
but when i look the definition of Where() extension method in Enumerable class
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
The type of the source is IEnumerable<T>
.
My question is: Array class does not implement IEnumerable<T>
but how can we still use the Where() extension method on an array ?
Upvotes: 2
Views: 1136
Reputation: 70652
Array doesn't implement IEnumerable<T>
, which you'd see if you tried to use something that requires IEnumerable<T>
with a variable actually typed as Array
. The type-specific array types (like int[]
as in your example) do implement IEnumerable<T>
, along with other generic types.
Upvotes: 3
Reputation: 13620
An array does implement IEnumerable as well as ICollection (and their generics) and a host of other ones
foreach (var type in (new int[3]).GetType().GetInterfaces())
Console.WriteLine(type);
Produces
Upvotes: 3