Attach an event to a dynamic object

I create a dynamic C # COM object object according to the following scheme:

dynamic pdfCreator = Activator.CreateInstance(
                       Type.GetTypeFromProgID("PDFCreator.clsPDFCreator"));

The clsPDFCreator class defines an event that raises eReady. But when I try to register an Eventhandler as

pdfCreator.eReady += _PDFCreator_eReady;

I get the error "Operator" + = 'cannot be applied to operands of type "dynamic" and "group".

How can I register an EventHandler for an event declared by a dynamic object?

+5
source share
3 answers

How about this:

public delegate void eReadyHandler();

static void Main(string[] args)
{
    var comType = Type.GetTypeFromProgID("PDFCreator.clsPDFCreator");
    dynamic pdfCreator = Activator.CreateInstance(comType);
    //dynamic pdfCreator = new PDFCreator.clsPDFCreator();

    //pdfCreator.eReady = null;
    pdfCreator.eReady += new eReadyHandler(_PDFCreator_eReady);
}

public static void _PDFCreator_eReady()
{

}
+5
source

Since the delegate type is not known at compile time, you must specify it. The delegate Actionmaps methods without parameters or return value:

pdfCreator.eReady += new Action(_PDFCreator_eReady);
+7
source

In the end, I used the following, as other parameters did not work. You may need to use the generic type <T> if your EventHandler is generic

pdfCreator.eReady += new System.EventHandler(_PDFCreator_eReady);
0
source

All Articles