2

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 ?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Survivor
  • 59
  • 7
  • 1
    Class `Array` doesn't implement `IEnumerable` when `T[]` *does* - `IEnumerable`. Since `Array` and `T[]` are *different* classes nothing wrong with them. – Dmitry Bychenko Oct 23 '14 at 06:41
  • If you read the ReferenceSource comments on `System.SZArrayHelper` it will shed *some* light on the problem. Hans Passant's explanation available here: http://stackoverflow.com/questions/11163297/how-do-arrays-in-c-sharp-partially-implement-ilistt/11164210#11164210 – Kirill Shlenskiy Oct 23 '14 at 06:42
  • 1
    Could you tell me documentation for T[ ] class i want to have a look at this class. – Survivor Oct 23 '14 at 13:47

2 Answers2

3

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

enter image description here

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
3

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.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • 1
    The type-specific array types do implement IEnumerable. how can i know ? can you provide any document please. Thanks. – Survivor Oct 23 '14 at 13:56
  • Well, for starters there is this passage on the MSDN documentation page for System.Array: `Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces` (http://msdn.microsoft.com/en-us/library/system.array.aspx) – Peter Duniho Oct 23 '14 at 16:13