| Create custom events |
Step 1: declare the delegate object, in the namespace not inside a class | namespace NazTek.Sample.EventHandling { public delegate void MyEventHandler(object sender, MyEventArgs e); } |
Step 2: define an EventArgs subclass. It is only useful if you want to pass data through the event otherwise you may simply use System.EventArgs class provided by the CLR | public class MyEventArgs : System.EventArgs { private string _arg; public string Message { get { return _arg; } } // note: you may pass any type through this subclass, including // custom classes and structs. Type used here is string public MyEventArgs(string arg) { _arg = arg; } } |
| Step 3: define the event publisher class. This is the class that contains the event to publish and the method that raises the event | public class MyEventPublisher { public MyEventPublisher() { } // declare the event to publish public event MyEventHandler MyEvent; // define a method to raise the event public void RaiseMyEvent() { OnMyEvent(this, new MyEventArgs("my event message")); } // define a method to encapsulate the actual raising of the event - best practice private void OnMyEvent(object sender, MyEventArgs e) { // raise the event if there's at least one subscriber if (MyEvent != null) MyEvent(sender, e); } } |
| Step 4: Define the event subscriber class. This is the class that contains a reference to the publisher class , explicitly attaches to the public event defined in that class, and defines the handler method | public class MyEventConsumer { // get a reference to the publisher and define the method to attach to the custom event. public MyEventConsumer(MyEventPublisher publisher) { // attach to the custom event publisher.MyEvent += new MyEventHandler(publisher_MyEvent); } // define the method to handle the custom event void publisher_MyEvent(object sender, MyEventArgs e) { System.Console.WriteLine("Message from my event: " + e.Message); } } |
Finally, create a console application to test the event handling process | class Program { static void Main(string[] args) { MyEventPublisher myPublisher = new MyEventPublisher(); MyEventConsumer myConsumer = new MyEventConsumer(myPublisher); myPublisher.RaiseMyEvent(); System.Console.ReadLine(); } } |