0

Wondering when you are going to re-assign a COM object, should you first dispose of the COM object?

public class DisposeTest : IDisposable
{
    public MyCOMObject MyObject { get; internal set; }

    public void ReAssign()
    {
        //Re-assign to new COM object
        MyObject = GetNewCOMObject();
    }

    public void Dispose()
    {
        if (MyObject != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(MyObject);
        }
    }
}

If you call ReAssign() multiple times it will create new instances of the MyCOMObject.

What I am not sure about is, should you first release the current MyObject before assigning a new value?

e.g. something like

public void ReAssign()
{
    //Release current object
    if (MyObject != null)
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(MyObject);
    }

    //Re-assign to new COM object
    MyObject = GetNewCOMObject();
}
NMGod
  • 1,937
  • 2
  • 12
  • 11
  • The answer is probably contained in the [Remarks section](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.releasecomobject?view=net-5.0#remarks) of the documentation. – GSerg Aug 31 '21 at 07:20
  • Independently from the .NET aspect (it's a managed world, so you don't really own the object, and BTW you should protect someone from calling Dispose multiple time otherwise you can release the RCW multiple times from this method which would not be logical - in other terms, follow "official" Dispose pattern), yes, it would be logical, otherwise, why would you add a Dispose method in the first place? – Simon Mourier Aug 31 '21 at 07:35
  • 1
    `should you first release the current MyObject before assigning a new value?` The _short_ answer is yes. – mjwills Aug 31 '21 at 07:56
  • It is wrong. You have a public getter, so cannot be sure that external code has stored a reference to the object. "COM object that has been separated from its underlying RCW" is the result, without a good way for the client programmer to find the reason. If you cannot wrap the object so it isn't exposed then you should trust the garbage collector. – Hans Passant Aug 31 '21 at 09:14
  • This was just an example bit of code, the actual does not expose the COM object – NMGod Aug 31 '21 at 23:35
  • Does this answer your question? [As of today, what is the right way to work with COM objects?](https://stackoverflow.com/questions/37904483/as-of-today-what-is-the-right-way-to-work-with-com-objects) – GSerg Sep 01 '21 at 20:52

0 Answers0