tags:

views:

44

answers:

1

Given the following code, can someone explain why I can pass a COM object as a value parameter but not as a reference parameter?

private void TestRelease()
{
    Excel.Workbook workbook = excel.ActiveWorkbook;
    ReleaseVal(workbook);       // OK
    ReleaseRef(ref workbook);   // Fail
}

private void ReleaseVal(Object obj)
{
    if (obj != null)
    {
        Marshal.ReleaseComObject(obj);
        obj = null;
    }
}

private void ReleaseRef(ref Object obj)
{
    if (obj != null)
    {
        Marshal.ReleaseComObject(obj);
        obj = null;
    }
}
+3  A: 

This has nothing to do with COM objects, it's simply a rule of C#. You cannot pass a reference type to an out or ref param unless the reference is of the same type as the parameter type.

Otherwise it would allow for unsafe scenarios like the following

public void Swap(ref Object value) {
  value = typeof(Object);
}

string str = "foo";
Swap(out str); // String now has an Type???

Now a string reference refers to an object who's type is Type which is wrong and very unsafe.

JaredPar
@JaredPar - ah, the fog is lifted.
Nick Hebb