Yes, this is well-known problem — C++/CLI is very different. Solution is also well-known, but it might look very unusual:
not only you are not allowed to do the check like
if(OnCppCliEvent != nullptr)
,
you also never need it!
In other words, just delete this check — the code will work correctly. If event handler is not added, the code invoking event will not be called, automatically. Hard to believe, but try it!
Here is the simplest usage pattern:
ref class EventSample {
public:
event System::EventHandler^ SomeEvent;
private:
void FireEvent() {
SomeEvent(this, gcnew System::EventArgs());
}
};
Event instance is not a method, it is a instance of some (hidden, auto-emitted per each event argument class used) class which has an invocation list in it, event per se is not called, handlers stored in the invocation lists are. I explained it in my article:
Dynamic Method Dispatcher[
^]. Sorry, the article in C# where the check for null is actually allowed and needed, but it is not so in C++/CLI.
—SA