Home > Software design >  CreateObject in C# to use a COM component
CreateObject in C# to use a COM component

Time:08-19

I have in my project a COM Interop where I use this code to make the call.

 object oCOM = CreateObject("SystemInterface.cApplication");

I don't think this way is better in C# code.

CodePudding user response:

A Simple change:

object oCOM = null;

        try
        {

            var oType = Type.GetTypeFromProgID("SystemInterface.cApplication");
            oCOM = Activator.CreateInstance(oType);

        }
        catch(Exception)
        {
            throw;
        }
        finally
        {
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oCOM);
        }

It is very important how you dispose of the object, be sure to use the code that is in "finally".

  • Related