1

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).

John Wu
  • 26,955

1 Answers1

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 strings. 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.

Erik Eidt
  • 34,819