Given the following code, will the ReleaseCOMObj() method release the original COM object, or will it implicitly create a copy and release that?
private void TestRelease()
{
Excel.Workbook workbook = excel.ActiveWorkbook;
// do stuff
ReleaseComObj(workbook);
}
private static void ReleaseComObj(Object obj)
{
if (obj != null)
{
Marshal.ReleaseComObject(obj);
obj = null;
}
}
Update: Changed method to static. See Passing COM objects as parameters in C# for an explanation as to why the Object parameter cannot be ref Object obj.
C# parameters are passed by reference.
Therefore, it will release the original COM object, but it won’t set the original variable to
null.To set the original variable to
null, change it to arefparameter, which passes a variable by reference. (and call it with therefkeyword)Also, by the way, the method should be
static, since it doesn’t usethis.