Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 382
tcpie Avatar asked Nov 28 '25 16:11

tcpie


1 Answers

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);
like image 112
Adriano Repetti Avatar answered Nov 30 '25 17:11

Adriano Repetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!