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 event) 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.
Let’s have a look at the code below to see how to use events.