Why do C# multidimensional arrays not implement IEnumerable<T>?
Solution 1:
The CLR has two different kinds of arrays: vectors which are guaranteed to be one-dimensional with a lower bound of 0, and more general arrays which can have non-zero bounds and a rank other than 0.
From section 8.9.1 of the CLI spec:
Additionally, a created vector with element type T, implements the interface
System.Collections.Generic.IList<U>
(§8.7), where U := T.
I have to say it seems pretty weird to me. Given that it already implements IEnumerable
I don't see why it shouldn't implement IEnumerable<T>
. It wouldn't make as much sense to implement IList<T>
, but the simple generic interface would be fine.
If you want this, you could either call Cast<T>
(if you're using .NET 3.5) or write your own method to iterate through the array. To avoid casting you'd have to write your own method which found the lower/upper bounds of each dimension, and fetched things that way. Not terribly pleasant.
Solution 2:
There is a workaround: you can convert any multidimensional array to an IEnumerable
public static class ArrayExtensions
{
public static IEnumerable<T> ToEnumerable<T>(this Array target)
{
foreach (var item in target)
yield return (T)item;
}
}
Solution 3:
Zero bound single dimensional arrays implements both IEnumerable
and IEnumerable<T>
, but multi-dimensional arrays, unfortunately, implements only IEnumerable
. The "workaround" by @Jader Dias indeed converts a multidimensional array to IEnumerable<T>
but with a huge cost: every element of an array will be boxed.
Here is a version that won't cause boxing for every element:
public static class ArrayExtensions
{
public static IEnumerable<T> ToEnumerable<T>(this T[,] target)
{
foreach (var item in target)
yield return item;
}
}