I recently answered this question on Code Review: Exists Method Implementation for Multidimensional Array in C#. The question is about determining whether an array of arbitrary dimension contains a specific element.
Based on this statement found in Arrays (C# Programming Guide) / Array overview:
Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.
and given the declaration int[,,,] array4
, I first gave the answer:
bool result = array4.Any(x => x == 1);
However, according to a comment of @JimmyHu, the compiler generates a:
Error CS1061 'int[,,,]' does not contain a definition for 'Any' and no accessible extension method 'Any' accepting a first argument of type 'int[,,,]' could be found (are you missing a using directive or an assembly reference?)
Apparently, the correct answer must be:
bool result = array4.Cast<int>().Any(x => x == 1);
This other attempt
bool result2 = ((IEnumerable<int>)array4).Any(x => x == 1);
does not work either and yields:
Error CS0030 Cannot convert type 'int[,,,]' to 'System.Collections.Generic.IEnumerable<T>'
Question: is the C# Programming Guide wrong on this point or I am missing something. Do arrays derive from Array
which implement the generic interface or not?