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).
1 Answer 1
Your suggested alternative assumes that the array is one dimensional. So, I guess you can't win them all... ;)
Arrays are a relatively primitive data type. I feel free using them internally to the implementation of an abstraction, just as I would using int
's and string
s. In those cases, the creator of the array and the consumer/user of the array is one and the same class, so the assumptions of zero-based index are natural, easy to verify, and relatively easy to change if there'd be some reason.
I would feel less free using an array as part of an abstraction for a client (even if only me later) to use, just as I feel more uncomfortable making an abstraction in terms of primitive int
or string
. In the case of creating an abstraction, I'd prefer handing out (or consuming) a dedicated type that represents a collection or an iterator/generator. This to protect both clients and me from the language-specific details of arrays (ints/strings), to create more type safety by introducing well defined types, and to try to move the abstraction up toward the client's domain and away from the implementation domain.
foreach
is not always appropriate, e.g. if working with parallel arrays, or if adding and removing items from the array.structs
(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.