Jacques Gaudin Jacques Gaudin - 4 days ago 6
C# Question

How can I add functionnality to COM object in c#?

I am new to COM and c# and I would like to add functionnality to a COM object that is exposed by a third-party program.

Intitially my intention was to inherit from the COM object class, but I found out it was not so straight forward (for example here).

Presently, I have two interfaces (namely

IComAuto
and
ComAuto
) and an associated class (
ComAutoClass
).

To add my custom methods to
ComAuto
objects, I have created a class
ComObjectWrapper
that inherits from this interface and implements it by storing a
ComAuto
object in a private field.

class ComObjectWrapper : ComAuto
{
private readonly ComAuto ComObj;

public ComObjectWrapper() : base()
{
ComObj = new ComAuto();
}

public short method1(object param)
{
return ComObj.method1(param);
}
...
}


I have a feeling this is not the best way to do this as I need to redirect any call to an original method to the internal
ComAuto
object.

I tried alternatively to inherit from
ComAutoClass
directly by setting the
Embed Interop types
property to
false
in VS2015. This led some method to return values as
object
when the code I have already written expects
string
. I would therefore have to go through all the written code to add some casts to
string
. Not ideal and moreover I don't have a full understanding of what
Embed Interop types
is.

I would appreciate if anyone could shed some light on this or point to some useful article (what I have found so far on MSDN sounds a bit cryptic for a beginner like me).

Answer

Sounds like a perfect use case for extension methods:

public static class ComAutoExtensions
{
    public static short Method1( this ComAuto com, object param )
    {
        return com.GetShortValue( param );
    }
}
Comments