Scott Hanselman

ReleaseComObject and IsComObject

January 04, 2006 Comment on this post [2] Posted in Programming
Sponsored By

We had a COM Object that needed to have ReleaseComObject called on it. This worked fine, and happily for a while. Then, someone created a .NET object with the exact same signature so that it might easily replace the use of the COM object. However, this new assemebly is NOT a COM Object, so it's extraordinarily bad to call ReleaseComObject on it (in that it totally doesn't work.)

So, here's a good best practice if you're doing some crazy crap like this:

if(Marshal.IsComObject(foo)) Marshal.ReleaseComObject(foo);

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
January 04, 2006 21:46
A good example of how this can come into play is if you have an old COM object and you use an interop from your managed code. Say you want to replace the COM object with a managed object. I don't want to get too far off track here but while you can make the managed code look like the old COM object via various COM attributes, you will run into problems if you run multiple AppDomains (NUnit, IIS) due to the managed client code to COM interop to managed server code path. A workaround for this is to gut the interop code, keeping the interface, name, and so on, and replacing the marshalling code with a direct call to the new managed component. Now you have managed client code that uses an "interop", which is really 100% managed, that then calls more managed code.

That all works unless your client code calls ReleaseComObject without checking IsComObject first. Since it isn't a COM object anymore you will get an InvalidCastException. Like Scott said, it's a good practice as it allows you to convert your legacy COM objects to managed code in the future with no client side code change.
January 05, 2006 1:15
I am amazed that ReleaseComObject is not a nop on everything not a COM object, or at least make that behaviour optional.

Do we really want to know via an exception that the operation is meaningless?


Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.