What number does an array’s index start from?
However, in the vast realm that is software development, it turns out there are 1 based arrays. I know, I know, I can hear some of you muttering under your breath, saying “I knew that,”.
Well, it was quite the revelation when I came across 1 based arrays. A little bit of research shows that 1 based arrays do exist, in a handful of languages, although 0 based arrays are more common, as shown here.
Now don’t get me wrong, if it’s the convention of the language, there is nothing wrong with a 1 based array. Where it becomes wrong is when you find 1 based arrays in a language whose convention is 0 based arrays.
I encountered this anomaly when I was programming a word plugin, which is done with C#, which, wait for it… uses 0 based arrays. So much to my frustration and surprise, attempting to access the first item via position 0 was met with a critical error. An hour later and with the help of my boss, we stumbled upon the solution – targeting position 1. The function worked flawlessly. Naturally, the next question that sprung to mind was what dark magic is this?
It turns out that Microsoft Office applications use 1 based arrays, going against the convention of the languages that MS Office applications are programmed in – namely VB and C#. Now, despite this *ahem* violation on Microsoft’s part, I could live with this if a) it was made clearer that this is the convention that Office applications use and b) if this was actually the convention for Office applications.
Yeah… it gets worse, for straight from the horse’s mouth:
“Most collections used in Office applications (except Access) are one-based, that is, the index number of the first item in the collection is 1. However, the collections in Access and some components, such as ADO and DAO, are zero-based, which is, the index number of the first item is 0.”
The key gem to take away here is that even the convention-breaking convention doesn’t stick to convention, and at this point, one needs to ask the real questions.
I’m not the only developer to encounter this strange phenomenon like Jacob Binstein did in his blog article here. What I hope that posts like this, or Jacobs achieve, is that they will show up in a google search and spare you some bewilderment, however small, as you try to decipher why your non-Access Office plugin fails to grab array item 0. I think that Jacob summed it up quite nicely when he said:
“If you’re using C#, arrays start at 0. Unless you’re using C# with an Office application, because then it starts at 1. Unless that Office application is Access, a Data Access Object (DAO), or an ActiveX Data Object (ADO), because then it’s back to 0.”