Recently, I had to develop a add-in for Outlook. Of course, I have to admit that I’m not an expert in C#. However, being used to Java, I quickly made me easy with this new language.
I just found something that makes me loosing a lot of time.
My add-in had to delete all the contacts from an Outlook contact folder. So naively, I write the following:
foreach (ContactItem contact in contactFolder.Items) { contact.Delete(); }
Simple isn’t it? But the result is that it doesn’t work. No compilation error, no runtime error, just that only half of the contacts were deleted. After some Google search to find why it could be wrong, I end up on the following: Working with Members of an Items Collection.
In this note, you can read that the element of a Outlook collection, should not be deleted using a classic loop. To delete them, you have to browse the collection in reverse order.
Even if I can’t understand the reason (it seems to be close to what causes a ConcurrentAccessException in Java), I found really frustrating that nothing warn you of such a behavior. For me, a good API should be implement in such a way that a normal expected behavior should at least generate exception.
To finish, here is the code that works:
for (int i = contactsFolder.Items.Count; i > 0; i --) { ContactItem contact = (ContactItem) contactsFolder.Items[i]; contact.Delete(); }