Visual C# Developer Center > Visual C# Forums > Visual C# General > Clarification about removing event handlers
Ask a questionAsk a question
 

AnswerClarification about removing event handlers

  • Thursday, November 05, 2009 12:26 AMAdrianAlexander Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    I have a class named MyClass that has an instance method named MyHandler .  There are two instances of MyClass , and an instance of another class named anotherClassInstance .  Within each instance of MyClass , the following code gets executed:

    anotherClassInstance.SomeEvent += MyHandler
    

    MyClass also contains the code:

    anotherClassInstance.SomeEvent -= MyHandler
    

    So my question is, when the latter code gets executed (for removing the event handler), will it only remove the handler for the specific MyClass instance in which its executed?  I worry that maybe it also removes the handler for the other MyClass instance.

Answers

  • Thursday, November 05, 2009 12:57 AMReed Copsey, Jr. Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    It will only remove the handler for the specific instance that's running.  If you have two instances of MyClass, and you subscribe to both of their event handlers, they are handled completely separately.  Unsubscribing works the same way, it just unsubscribes that one time.

    You don't need to worry.


    Reed Copsey, Jr. - http://reedcopsey.com

All Replies

  • Thursday, November 05, 2009 12:57 AMReed Copsey, Jr. Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer

    It will only remove the handler for the specific instance that's running.  If you have two instances of MyClass, and you subscribe to both of their event handlers, they are handled completely separately.  Unsubscribing works the same way, it just unsubscribes that one time.

    You don't need to worry.


    Reed Copsey, Jr. - http://reedcopsey.com