Thursday, July 12, 2007

Avoid Pitfalls

The following code snippet is error-prone:

for (int i = 0; i <>SelectedIndices->Count; i++)
{
/* do something */
}

Why? listView->SelectedIndices->Count may change in the loop. For example, if we delete one item in listView->SelectedIndices collection a time, listView->SelectedIndices->Count will be 1 less than the the value in last loop.

Another common pitfall is, when deleting items in a collection, items after the deleted item are shifted automatically. Therefore, we are to delete some items one by one in a collection according to their initial indices, we need to delete them backwards.

No comments: