It is very, very common to see code like this:
for (int i = 0; i < array.Length; i++)
{
DoSomething(array[i]);
}
The above code makes certain assumptions about arrays (which apparently hold true most of the time, but not all the time). Wouldn't it be more explicit and more forward-compatible to use something like this instead?
for (int i = array.GetLowerBound(0); i <= array.GetUpperBound(0); i++)
{
DoSomething(array[i]);
}
Why is the former format so widely accepted and used?
(I know we could use foreach
, but let's assume that there is some reason that would not work for us in this specific case).
foreach
is not always appropriate, e.g. if working with parallel arrays, or if adding and removing items from the array. – John Wu Jan 11 '17 at 0:51structs
(or whatever they call them in C#) with the array bounds tightly attached, then maybe you gotta point. but array indexing should be simply translatable to pointer arithmetic and that is far easier when each dimension of the array has 0 as the origin. also check out this. – robert bristow-johnson Jan 11 '17 at 9:05