7

I've been banging my head against the wall for 25 minutes trying to figure out why I can't access the 'first' index of an array, which I was trying to do with array[0]. I kept getting an Array Index Out of Bounds Exception. Just to see what would happen, I tried using array[1]...and it worked. Perfectly. I have no idea why.

for (int i = 1; i < itemCounter+1; i++)
{
     if (explorer.CurrentFolder.Items[i] is Outlook.MailItem)
     { //Do something }
}

The whole thing works fine. What's going on here?

Jake
  • 3,142
  • 4
  • 30
  • 48
  • 2
    What does the documentation say? Sounds to me like `Items` is some wrapped collection type which overloads `operator []` and throws an `IndexOutOfRangeException` for index 0. Also note that VB arrays are 1-indexed, so perhaps this is a compatibility shim? (sounds odd to me, but hey, who knows.) Can't you just peek at the collection in the debugger? – Ed S. Jul 16 '12 at 20:23
  • 2
    Yes, most collections in the Office Object Model are one-based. I agree that the OOM documentation is appallingly poorly-written. – Douglas Jul 16 '12 at 20:28

2 Answers2

17

It appears that the Outlook Object Model is part of the Office Object Model, and as http://msdn.microsoft.com/en-us/library/aa189134%28v=office.10%29.aspx states,

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.

Also, http://msdn.microsoft.com/en-us/library/522xhsa3%28v=vs.90%29.aspx specifically tells us that

To access the first item of a collection in the object model of a Microsoft Office application, use the index 1 instead of 0.

MvanGeest
  • 9,536
  • 4
  • 41
  • 41
  • Fascinating! In my research into this subject, I skipped articles like the first one you linked to, because it specifically says Windows XP at the top, and I'm using Windows 7 (I had no idea it carried over!). The second one is really what I should have been looking for, but even through my Google searches and looking through various MSDN (and others') tutorials, I never found a link or an explanation. Thanks so much! – Jake Jul 16 '12 at 20:33
1

Yeah, it looks like Items returns a collection object, and those are known to be screwy when accessed with an array modifier like that. You should be able to do .ToArray() to get the behavior you expect, otherwise you could simply use foreach var item in items and get everything in the folder, with a construct that's guaranteed to terminate, too.

tmesser
  • 7,558
  • 2
  • 26
  • 38
  • Similar to what I said in my comment to MvanGeest, I skipped articles like the one you linked to, because it specifically mentions VBA, and I'm using C# .NET, so I had no idea that things carry over like that between languages. The whole thing is very strange to me...I'll definitely be using the .ToArray() method so everything works like it should, thanks! – Jake Jul 16 '12 at 20:35