-1

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

Initially 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).

1
  • 1
    No real happy answers here, COM uses a hyper-pure interface-based paradigm. Using inheritance is still possible by deriving from ComAutoClass, but sure, you can no longer embed the interop types. Having one more DLL to deploy is not the end of the world. Technically you can embed it yourself, use a decompiler like ILSpy or Reflector and copy/paste ComAutoClass. Rename it. It is however absolutely crucial that the COM component is never going to change again. Commented Nov 30, 2016 at 15:06

1 Answer 1

1

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 );
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It does indeed! Thanks I didn't know about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.