Casting Statement as COM Object

138 views Asked by At

So I know if you assign a variable to a COM Object like Matrix mtx = form.Items.Item("mtx").Specific; it needs to be released with Marshal.ReleaseComObject(mtx);

But what if I were to cast it as a COM Object like ((Matrix)form.Items.Item("mtx").Specific).AddRow(1);. Now I have no variable reference. Does this get released? Does a reference get created in memory and now it's stuck there until the application is killed?

Take this extension method:

 public static T BindControlAs<T>(this BaseFormHandler handler, string itemId) where T : class
    {
        if (!(handler.form.Items.Item(itemId).Specific is T control))
            throw new InvalidOperationException($"{typeof(T)} failed to bind {itemId}");

        return control;
    }

This extension method is used only for my forms COM Objects. Now on my form I can do the following

this.BindControlAs<Matrix>("mtx").AddRow(1);

Again I have not assigned this to a variable to allow me to Marshal.ReleaseComObject.

So my question is does a cast or the extension method create a new instance of my COM Object and never gets released and just sits in memory or does it get removed once the statement has been executed? If it never gets released, is there a way to ensure it does without the Marshal.ReleaseComObject and assigning it to a variable?

1

There are 1 answers

3
bic On BEST ANSWER

The code in your answer would create a reference that is not assigned to a variable, and would be stuck.

You can clean this up by calling Calling GC.Collect and then GC.WaitForPendingFinalizers instead of Marshal.ReleaseComObject for every COM object.

This is better than assigning every single COM object and then releasing it when you are done with it.