Shiv
Shiv

Reputation: 1404

Check if a specific event handler method already attached

Related to this question, Check if an event already exists

but the difference is I just want to know if a particular method is attached to the event. So there may be other methods attached, but I just want to know if a particular one exists.

My environment is C# in dotnet 4.0.

E.g.

Event += MyMethod1;
Event += MyMethod2;

// Some code
if (MyMethod1IsAttachedToEvent())
{
    // Achieved goal
}

Is this possible?

Upvotes: 17

Views: 47005

Answers (4)

NameSpace
NameSpace

Reputation: 10177

Late answer here. I believe Parimal Raj answer is correct, as I could not find a way to directly access the events. However, here are two methods I created to get around this:

  1. Delete before adding. If the method isn't there, I did not receive an error trying to delete the nonexistant method. This way you can insure the invocation list calls method1 only once.

    Event -= MyMethod1;
    Event += MyMethod1;
    
  2. The objects you are adding an event to may have a .Tag property. You can use the Tag to store info about the methods you already added. Here I only have one method, so I just need to check if Tag is null. But more complicated scenarios can be handled this way:

    if(control.Tag == null)
    {
         //ony added once, when tag is null
         control.TextChanged += new EventHandler(validate); 
         control.Tag = new ControlTag();
    }
    

Upvotes: 6

Benjiman
Benjiman

Reputation: 420

foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
{
    if ( existingHandler == prospectiveHandler )
    {
          return true;
    }
}

loop through the delegates using the GetInvocationList method.

Upvotes: 5

Parimal Raj
Parimal Raj

Reputation: 20575

No. You cannot.

The event keyword was explicitly invented to prevent you from doing what you want to do. It makes the delegate object for the event inaccessible so nobody can mess with the events handlers.

Source : How to dermine if an event is already subscribed

Upvotes: 24

TalentTuner
TalentTuner

Reputation: 17556

Event.GetInvocationList().Any(x => x.Method.Name.Equals("yourmethodname"));

Upvotes: 5

Related Questions