JimmyJimm JimmyJimm - 1 month ago 7
Vb.net Question

Scope of event handler after object instantiation again

I have a global variable:

Public myPerson As New Person

Then I attach an event handler:

AddHandler myPerson.OnClose, AddressOf DoWhatever

Then somewhere else in the program I recreate my object:

myPerson = New Person

Will my event handler still be attached to new myPerson, or do I need to add it again?


Does my event handler will be still attached to new myPerson or do i need to add it again?

Event handlers are specific to each instance of the class. When you do myPerson = New Person you instantiate a completely new instance of the Person class that has its own references, variables, and events.

Remember that just because you refer to the same variable it doesn't mean its the same class instance. A class instance can be referenced by multiple variables. For example, here:

Dim Person1 As New Person
Dim Person2 As Person = Person1
Dim Person3 As Person = Person1

AddHandler Person1.OnClose, AddressOf DoWhatever

all three variables refer to the very same instance of the Person class. So if you'd call something on Person3 that raises the OnClose event, the event handler would still get called.

If answer is -no it will be disposed

The handler will only be disposed/detached if you detach it manually or if the Garbage Collector disposes/collects your first instance. In my above example, reinstantiating/changing Person1 will not remove the event handler since Person2 and Person3 still reference the class instance.

This fiddle illustrates what I'm talking about: https://dotnetfiddle.net/8XiH19

As you see the only person reported closed is John, referenced by Person2, while calling myPerson.Close() on the newly instantiated person yielded nothing.

what if i would add the same handler again, would it be then called twice as i would have two same handlers attached twice?

No. As said above the event handler is specific to the class instance, not the variable.