2

I have a class X and this class have a event: EventX.

And I have a class B, I register event EventX of objectX to a eventhandler HandlerB of class B.

X objectX = X.GetStaticObject();
objectX.EventX += HandlerB;

How to check EventX of objectX contained eventhandler HandlerB. Thanks.

Notes: objectX is a static global which event can be registered from anywhere with any objects which are not object B.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Leo Vo
  • 9,980
  • 9
  • 56
  • 78

3 Answers3

4

To check that specifically your HandlerB was registered, you can use Delegate.GetInvocationList() method to get appropriate info.

EDIT:

After V4Vendetta comment I tried to compile code and it failed. I slightly changed it.

To be able to do that check, method Test should be added to X (I assume that it's static, otherwise use this instead of X):

public static void Test(Delegate delegateToTest)
{
   if (X.EventX != null)
   {
       foreach (Delegate existingHandler in X.EventX.GetInvocationList())
       {
           if (existingHandler == delegateToTest)
           {
               // registered
           }
       }
    }
}

And then test from somewhere where HandlerB is accessible:

X.Test(new EventHandler(HandlerB));
msergey
  • 592
  • 1
  • 4
  • 12
  • @V4Vendetta: you are right. I did not check it in VS and completely forget that it may cause error. However I edited code to make it work. – msergey Jul 13 '11 at 09:53
3

If it is not null, it is registered (though it might be with an empty handler).

if(objectX.EventX != null)
{
  // registered!
}

As far as I know, you can't tell what is registered with it. Being able to would defeat the point of having an event in the first place (decoupling code and double dispatch).

Oded
  • 489,969
  • 99
  • 883
  • 1,009
1

If you want to prevent an event handler to be registered twice for the same event, you could remove it before you register it - something like this:

objectX.EventX -= HandlerB; 
objectX.EventX += HandlerB;

This can be done in the registering code, or even in the event itself. Have a look at this question for details.

Note: removing HandlerB should not fail, even if it was not registered before! (Unless somebody changed the remove part in an explicit event definition to do so.)

Community
  • 1
  • 1
Stephan
  • 4,187
  • 1
  • 21
  • 33