In C#, if you want to iterate over a collection of something, you can use the following pattern to ensure that each element in the collection is visited once...

foreach (object aThing in aCollectionOfThings)
{
    aThing.DoWork();
}

However, if you are using VSTO 2005 SE you have to be careful because if you attempt to access a collection which is empty you do not get an empty collection returned; instead a COM error is thrown. This being the case, you should use the following pattern to iterate over a collection...

try
{
    foreach (Range aRange in aCell.Precedents)
    {
        //Do work with aRange
    }
}

catch { } //Ingnore the COM error

finally
{
    //Do stuff that needs to be done regardless of errors or otherwise.
}

Technorati tags: