In this code snippet, we will take a look at events in C#.
A class(subscriber class) can subscribe to an event of another class(publisher class). The publisher class notifies the subscriber class every time the event occurs. This works by using delegates. The subscriber will pass its delegate to the publisher class to “make a subscription” to its event. When the event occurs the publisher will call the delegate(callback method) that was provided to it by the subscriber when it “subscribed” to the event. This is how (for example button press events) events work in .NET. This principle of operation is also called the observer pattern.
See this post if you want to know how to send event arguments(pass data with the event) along with your events.
Unsubsribing: The subscriber classes should always unsubscribe from the publisher class before being disposed of to prevent memory leaks. This can be done by using -= (see in the example below). I would recommend you do this in the destructor of your subscriber class.
Lambda Expression: If you subscribe to an event using an anonymous function(lambda expression) you can’t easily unsubscribe. So only use anonymous functions to subscribe to events when you know you won’t need to unsubscribe for the entire lifecycle of your program.
Let’s have a look at the code below to see how to use events.