views:

362

answers:

2

I'm updating some old Managed C++ code with lines like this:

instanceOfEventSource->add_OnMyEvent( 
    new EventSource::MyEventHandlerDelegate(this, MyEventHandlerMethod) );

where

  • EventSource is the class that publishes events
  • instanceOfEventSource is an instance of that class
  • EventSource::MyEventHandlerDelegate is the delegate type for the event
  • MyEventHandlerMethod is a (non-static) method within the current class (of which "this" is an instance) with the signature matching EventSource::MyEventHandlerDelegate

What is the right syntax for this in C++/CLI?

+1  A: 

The syntax is similar to C#'s, in other words, += is overloaded to make this possible:

instanceOfEventSource.MyEvent +=
    gcnew EventSource::MyEventHandlerDelegate(this, &MyClass::MyEventHandlerMethod);

Analogously for removal. Unlike C#, however, you may not omit the explicit instantiation of the event handler delegate so this produces quite long-winded code.

Konrad Rudolph
Per @OJ's post, I had to use gcnew, and I also found I had to write "@MyClass::MyEventHandlerMethod" instead of just "MyEventHandlerMethod". But this took me where I needed to go -- thanks!!
Eric
Right about `gcnew`, I just didn't change this part of the code. And right about the method, as well. :-/
Konrad Rudolph
+1  A: 

Should you not be using gcnew?

OJ
This would be better as a comment on Konrad's post. It's not an answer to the question. You're right though.
Stu Mackellar
In the new C++/CLI you do need to use gcnew, but in the original Managed C++ you did not. So it's not in my question, but I do hope Konrad will update to include that in his answer.
Eric
Stu, don't agree. It could have been part of the solution :)
OJ