tcpie
tcpie

Reputation: 431

How can I clear event subscriptions in C++/CLI?

I have a class Foo, which has a public event Bar. I need to clear all subscriptions to Bar.

In C# it is as easy as (within class Foo):

public void RemoveSubscribers() { this.Bar = null; }

(see also this question)

How do I do this in C++/CLI? I cannot set Bar to nullptr: the compiler spits out the error

Usage requires 'Foo::Bar' to be a data member

I've had a look at the RemoveAll method of Bar, but I don't understand what I should supply as arguments...

EDIT 1: For clarity, Bar was declared as follows:

public ref class Foo
{
public:
    event MyEventHandler^ Bar;
};

Upvotes: 3

Views: 1635

Answers (1)

Adriano Repetti
Adriano Repetti

Reputation: 67118

C++/CLI hides underlying backing store (the delegate) even within the class so you can't simply set it to nullptr. Because you can't rely on default event implementation then you have to do it by yourself:

private: EventHandler^ _myEvent;

public: event EventHandler^ MyEvent 
{
    void add(EventHandler^ handler)
    {
        _myEvent += handler;
    }

    void remove(EventHandler^ handler) 
    {
        _myEvent -= handler;
    }
}

Now you can simply nullify myEvent delegate:

_myEvent = nullptr;

This, of course, will change how you'll invoke it too (same as C# instead of C++/CLI short version):

EventHandler^ myEvent = _myEvent;
if (myEvent != nullptr)
    myEvent(this, e);

Upvotes: 1

Related Questions