tags:

views:

44

answers:

1

Working with Excel interop, I'm trying be very careful about not implicitly creating any objects (c.f. two dot rule) and ensuring that everything is properly released.

If I create an System.Object from a COM object property, is that object a COM object? To clarify, take the case of the cell object below. Do I need to call Marshal.ReleaseComObject(cell) or not?

public static float RangeLeft(ref Excel.Worksheet sheet, int row, int col)
{
    float returnValue;
    object cell = null;
    Excel.Range range = null;

    try
    {
        cell = sheet.Cells[row, col];
        range = sheet.get_Range(cell, Type.Missing);
        returnValue = (float)range.Left;
    }
    catch (COMException comex)
    {
        Debug.WriteLine(comex.Message);
        throw;
    }
    finally
    {
        if (cell != null)
        {
            Marshal.ReleaseComObject(cell);
            cell = null;
        }
        if (range != null)
        {
            Marshal.ReleaseComObject(range);
            range = null;
        }
    }
    return returnValue;
}
+1  A: 

I believe that you do have to release it, because I don't think that there is actually any such thing as a cell object -- a cell is actually another Range object, it just happens to cover only one cell.

Jay
I guess I'll just have to run it and find out. I'll embed a try-catch block within the finally{} block just in case.
Nick Hebb