0

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?

9
  • 1
    Does this answer your question? Why do C# multidimensional arrays not implement IEnumerable<T>? Commented Mar 19, 2021 at 15:05
  • 1
    Does this answer the question about the programming guide? Even Jon Skeet says: " it seems pretty weird to me". Commented Mar 19, 2021 at 15:07
  • 1
    The guide is an over-simplification -- only single-dimensional arrays implement IEnumerable<T> Commented Mar 19, 2021 at 15:08
  • 1
    it kinda does answer it. the guide claims all arrays implement IEnumerable and IEnumerable<T>, whereas the answer says _multidimensional_arrays only implement IEnumerable. so yes, technically the guide is wrong - or at least imprecise. Commented Mar 19, 2021 at 15:17
  • 2
    I posted this as a new issue on github: Text unclear about arrays implementing IEnumerable<T> #23399. Commented Mar 19, 2021 at 15:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.