Could someone please be kind enough to explain why there is only a static/shared version of ForEach for arrays?
IE: ForEach<T>(T array[], System.Action(Of T) action[])
I assume this has something to do with the type inference requirements of implementing an instance method, but when you declare your array you provide type right?
One problem with arrays is that there’s nowhere to document the instance methods which are available only on “vectors”. A “vector” is a single-dimensional array with a base of 0 – so anything representable as
T[]in C# is a vector, but aT[,]isn’t, for example.That means not every instance of
Arrayshould have the method – and even if it did, how would you represent theT? Each array type is separate, and there’s no generic type in .NET which is a base class for all arrays. All we’ve got isArray.So, given that we have to introduce the type parameter somewhere in the type system, and given that we’re also restricting it to “vector” types, a static method seems an appropriate workaround.
Note how this is not the case with
List<T>, where we already have the type parameter so can create a simple instance method.It’s also worth thinking about when using
Array.ForEachactually ends up with cleaner code than just using aforeachloop. I would typically only use it when I’d already got a delegate to execute on each element. Otherwise the language construct feels cleaner, and it certainly more flexible in its ability to return or break out of the loop without an exception.