Add and remove event handlers dynamically in .NET

.NET lets you add and remove Event Handlers dynamically
on the fly. Your code can start and stop handling events at any time during
program execution. Also, you can tie the same code (event handler) to multiple
events similar to the Handles clause in VB.NET.

The VB.NET AddHandler and RemoveHandler
statements allow this behavior. Both statements take two arguments: the name of
the event to handle and the name of the procedure that will handle the event.

Dynamically add and remove an event handler in VB.NET:

Public Class MyClass
'
' Declare the event to be raised.
'
Public Event MyEvent
Sub RaiseMyEvent()
'
' Method to raise the event.
'
RaiseEvent MyEvent
End Sub
End Class
Public Class Test
Sub TestEvent()
'
' Create the object that raises the event you want to handle.
'
Dim myobj As New MyClass()
'
' Associate the code to be executed (event handler) with the event.
'
AddHandler myobj.myEvent, AddressOf MyEventHandler
'
' Tell the object to raise the event. It will be handled by sub MyEventHandler.
'
myObj.RaiseMyEvent()
'
' Dis-associate the handler from the event.
'
RemoveHandler myobj.myEvent, AddressOf MyEventHandler
'
' Tell the object to raise the event. It will NOT be handled by sub MyEventHandler.
'
myObj.RaiseEvent()
End Sub
Sub MyEventHandler()
'
' Code to be executed when the event is raised.
'
MsgBox("I caught the event!")
End Sub
End Class

C# lets you to do the same using delegates which is
what VB uses behind the scenes. To learn more about delegates and how
to define event argumentsclick
here.

namespace MyClass
{
public delegate void MyEventHandler(EventArgs e);
public class MyClass
{
// Declare the event to be raised.
public event MyEventHandler MyEvent;
public void RaiseMyEvent()
{
// Method to raise the event.
MyEvent(EventArgs.Empty);
}
} //MyClass
} //namespace
public class Test
public void TestEvent()
{
//
// Create the object that raises the event you want to handle.
//
MyClass myobj = new MyClass();
//
// Associate the handler with the event.
//
myobj.MyEvent += new MyEventHandler(MyHandler);
//
// Tell the object to raise the event. It will be handled by sub MyHandler.
//
myObj.RaiseMyEvent()
//
// Dis-associate the handler from the event.
//
myobj.MyEvent -= new MyEventHandler(MyHandler);
}
public void MyHandler()
{
// Code to be executed when the event is raised.
MessageBox.Show("I caught the event!");
}
}