Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# event null check (from another class)

I set an lambda expression as a event handler to a event

proxy.SomeEvent += (sender, e) => { doSomething(); };

But when debugging I found doSomething() was executed twice because somehow the above event assignment statement was executed twice.

So I want check whether the proxy.SomeEvent is null before calling the event assignment statement,like:

if(proxy.SomeEvent == null)
{
    proxy.SomeEvent += (sender, e)=> { doSomething(); };
}

But I get a compiler error The event 'Proxy.SomeEvent' can only appear on the left hand side of += or -=

Since it is not possible to remove a lambda expression event handler by the -= operator, is there other way which enables me to check whether an event has already been assigned?

like image 693
user753503 Avatar asked Dec 02 '25 04:12

user753503


1 Answers

There is no (standard) way to "inspect" what an event handler has.

The only valid forms (for external access) are:

obj.Event += Handler;
obj.Event -= Handler;

It when accessed outside the class it does not allow any method invoked upon the Event nor does it support any other operators.

However, if you write it in such a way that you keep the original handler then you can remove it before-hand.

public Handler(object sender, EventArgs) {
    ...
}

// remove if already added (does nothing if it was not added)
// there is no (standard) way to check if it was added so this
// is just a pre-emptive remove
proxy.SomeEvent -= Handler;
// and add the handler
proxy.SomeEvent += Handler;

I'm not saying this is the best/a good way (e.g. why is the handler allowed to be assigned multiple times for "the same" handler?), but it is one approach I have used on occasion.

Happy coding.